C++中的输入流。cin unget()函数有些混淆。

5

我有关于 cin.unget() 函数的一些疑惑,希望有人能够解答。请考虑以下代码:

void skip_to_int()
{
    if (cin.fail()) {                   // we found something that wasn’t an integer
        cin.clear();                    // we’d like to look at the characters
        for (char ch; cin>>ch; ) {      // throw away non-digits
            if (isdigit(ch) || ch=="-") {
                     cin.unget();       // put the digit back,
                                        // so that we can read the number
                     return;
            }
        }
    }
    error("no input");                  // eof or bad: give up
}

如果cin.unget()将数字放回到输入流中再次读取,那么我不是会重复读取同一个字符进行条件检查,从而陷入无限循环吗?
1个回答

4
让我们更详细地了解一下 skip_to_int
 if (cin.fail()) {

如果最后一次输入有误

       cin.clear();

清除标志并寻找下一个好的数据。
       for (char ch; cin>>ch; ) {

获取一个字符
            if (isdigit(ch) || ch=="-") {

如果字符是我们想要的字符。
                 cin.unget();

把它放回流中

                 return;

退出函数!!!
            }

否则循环回到获取下一个字符。
        }

没有更多的字符了,退出循环。

  }

  error("no input");

unget 执行后,函数将立即返回,结束循环和函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接