我想读取一个 istream 并将其分成标记,使用 istream::peek
检查序列中的下一个字符。但是,如果不在输入末尾插入某个字符,我就无法结束循环。
有没有办法检查下一个字符是否是输入的结尾?我试过 while(c != is.eof()) 但它不起作用。
void calculator(istream& is){
//Some structures
char c = '0';
while (c != '.'){
c = is.peek();
switch (c){
//Some operations with is
//is.ignore(1);
//is >> variable;
}
}
int main (void){
calculator (cin);
}
最佳答案
来自 std::istream::peek()
的 reference documentation它说:
Return value
If
good() == true
, returns the next character as obtained byrdbuf()->sgetc()
Otherwise, returnsTraits::eof()
.
所以你应该根据Traits::eof()
检查返回值:
int c = 0; // Note peek() returns `int_type` actually not char
while (c != '.'){
c = is.peek();
if(c == std::char_traits::eof())
{
break;
}
switch (c){
//Some operations with is
//is.ignore(1);
//is >> variable;
}
}
关于c++在循环中使用istream::peek检查cin的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35875936/