为什么 cin inside while 不停地获取用户输入?

Why cin inside while doesn't stop to get user input?

我现在开始学习 C++,所以我想这将是一个非常简单的新手问题。

嗯,为什么 while 中的 "cin >> x" 行不停止循环以获取用户输入(如果用户输入字符而不是数字)?

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{
    int x = 0;
    cout << "Please, enter x: ";
    cin >> x;
    while (!cin)
    {
        cout << "Please, it must be a number!\n";
        cin >> x;
    }
    cout << "Thanks!.";
    cin.ignore();
    cin.ignore();
}

我学习 C++ 才两天,所以我完全不知道 "cin" 到底是什么。我尝试使用 "cin.sync()" 和 "cin.clear()",但仍然没有成功。 而且我知道不可能做 "cin=true" 或 "cout << cin".

这样的事情

如果用户输入一个字符,它会取字符的 ascii 值,所以它不会停止。 要停止循环,请输入 0.

嗯,你的程序应该稍微修正一下

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

int main()
{
    int x = 0;
    cout << "Please, enter x: ";
    cin >> x;
    while (!cin)
    {
        cin.clear();
        cin.ignore(10000, '\n');
        cout << "Please, it must be a number!" << endl;
        cin >> x;
    }
    cout << "Thanks!.";
}

这样就可以正常工作了。有关它的更多信息 here。一般情况下,你需要把cin里面所有的错误都清除掉。