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

input stream in C++. A little confusion with cin unget() function

任何人都可以消除我对 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() 将数字放回输入流中再次读取,我会不会得到 cin>>ch 相同的字符再次检查条件,因此陷入无限循环?

让我们仔细看看skip_to_int

 if (cin.fail()) {

如果上次输入错误

       cin.clear();

清除标志并寻找下一个好的数据

       for (char ch; cin>>ch; ) {

获得一个角色

            if (isdigit(ch) || ch=="-") {

如果角色是我们想要的角色

                 cin.unget();

将其放回流中

                 return;

退出函数!!!

            }

否则循环获取下一个字符

        }

没有更多字符,退出循环

  }

  error("no input");

紧跟在 unget 之后的函数 returns,与函数一起结束循环。