C++ istream::putback() 函数



C++ 的std::istream::putback() 函数用于将一个字符放回输入流缓冲区。这允许重新读取之前从流中提取的字符。当调用此函数时,该字符将放置在缓冲区的开头,使其可用于后续的输入操作。

语法

以下是 std::istream::putback() 函数的语法。

istream& putback (char c);

参数

  • c − 表示要放回的字符。

返回值

此函数返回 basic_istream 对象(*this)。

异常

如果抛出异常,则对象处于有效状态。

数据竞争

修改流对象。

示例

在以下示例中,我们将考虑 putback() 函数的基本用法。

#include <iostream>
#include<sstream>
int main()
{
    std::istringstream a("Welcome");
    char x;
    a >> x;
    std::cout << "Read: " << x << std::endl;
    a.putback(x);
    a >> x;
    std::cout << "Read again: " << x << std::endl;
    return 0;
}

输出

以上代码的输出如下:

Read: W
Read again: W

示例

考虑以下示例,我们将放回多个字符。

#include <iostream>
#include<sstream>
int main()
{
    std::istringstream a("XYZ");
    char b;
    a >> b;
    std::cout << "Read: " << b << std::endl;
    a.putback(b);
    a >> b;
    a.putback(b);
    a >> b;
    std::cout << "Read again: " << b << std::endl;
    a >> b;
    std::cout << "Read again: " << b << std::endl;
    return 0;
}

输出

以下为上述代码的输出:

Read: X
Read again: X
Read again: Y

示例

让我们看一下以下示例,我们将结合使用 putback() 函数和 peek() 函数。

#include <iostream>
int main()
{
    std::istream& is = std::cin;
    char x;
    std::cout << "Enter A Character : ";
    x = is.peek();
    std::cout << "Peeked Character: " << x << std::endl;
    is.get(x);
    std::cout << "Read Character: " << x << std::endl;
    is.putback(x);
    x = is.peek();
    std::cout << "After putback, Peeked Again: " << x << std::endl;
    return 0;
}

输出

如果我们运行以上代码,它将生成以下输出:

Enter A Character : ABC
Peeked Character: A
Read Character: A
After putback, Peeked Again: A
istream.htm
广告

© . All rights reserved.