C++ basic_ios 库 - unget
描述
它用于取消字符。
声明
以下是 std::basic_istream::unget 的声明。
basic_istream& unget();
参数
none
返回值
返回 basic_istream 对象 (*this)。
异常
Basic guarantee − 如果抛出异常,则对象处于有效状态。
数据竞争
修改流对象。
示例
在下面的 std::basic_istream::unget 示例中。
#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.unget();
std::cin >> n;
std::cout << "You entered a number: " << n << '\n';
} else {
std::string str;
std::cin.unget();
getline (std::cin,str);
std::cout << "You entered a word: " << str << '\n';
}
return 0;
}
输出应该是这样的 −
Please, enter a number or a word: 7791 You entered a number: 7791

