c++在循环中使用istream::peek检查cin的结尾

标签 c++

我想读取一个 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 by rdbuf()->sgetc() Otherwise, returns Traits::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/

相关文章:

c++ - 在排序模板函数中确定 2 个数组差异组件

c++ - 帮我评价一下这个选角

c++ - 如何获取类型的唯一序列 c++ : (A, B, A, B, C) =>(A, B, C)

c++ - 运算符与函数行为

c++ - namespace::variable 的多重定义,即使使用 ifndef

c++ - 来自不同命名空间的 friend 方法

c++ - 什么是 : throw 0 do/mean? 是 "bad"吗?

c++ - MS Access 中 NZ 函数的 ADO 等价物?

c++ - 是否可以在 C++ 的类中初始化静态常量成员对象?

c++ - 在 autotools 项目中添加 C++ 支持?