C++ basic_ios 库 - putback
描述
它用于放回字符。
声明
以下是 std::basic_istream::putback 的声明。
basic_istream& putback (char_type c);
参数
c − 要放回的字符。
返回值
返回 basic_istream 对象 (*this)。
异常
Basic guarantee − 如果抛出异常,则对象处于有效状态。
数据竞争
修改流对象。
示例
在下面的 std::basic_istream::putback 示例中。
#include <iostream>
#include <string>
int main () {
std::cout << "Please, enter a number or a word: ";
char c = std::cin.get();
if ( (c >= '0') && (c <= '9') ) {
int n;
std::cin.putback (c);
std::cin >> n;
std::cout << "You entered a number: " << n << '\n';
} else {
std::string str;
std::cin.putback (c);
getline (std::cin,str);
std::cout << "You entered a word: " << str << '\n';
}
return 0;
}
输出应该是这样的 −
Please, enter a number or a word: pocket You entered a word: pocket

