C++ basic_ios 库 - peek
描述
它用于查看下一个字符。
声明
以下是 std::basic_istream::peek 的声明。
int_type peek();
参数
none
返回值
返回输入序列中的下一个字符,而不提取它:该字符保留为要从流中提取的下一个字符。
异常
Basic guarantee − 如果抛出异常,则对象处于有效状态。
数据竞争
修改流对象。
示例
在下面的 std::basic_istream::peek 示例中。
#include <iostream>
#include <string>
#include <cctype>
int main () {
std::cout << "Please, enter a number or a word: ";
std::cout.flush();
std::cin >> std::ws;
std::istream::int_type c;
c = std::cin.peek();
if ( c == std::char_traits<char>::eof() )
return 1;
if ( std::isdigit(c) ) {
int n;
std::cin >> n;
std::cout << "You entered the number: " << n << '\n';
} else {
std::string str;
std::cin >> str;
std::cout << "You entered the word: " << str << '\n';
}
return 0;
}
输出应该是这样的 −
Please, enter a number or a word: foobar You entered the word: foobar

