为什么 cin in in 而没有停止获取用户输入?

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

本文关键字:in 获取 用户 输入 cin 为什么      更新时间:2023-10-16

我现在从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()"answers"cin.clear()",但仍然没有运气。我知道不可能执行"cin=true"或"cout <<"cin。"

好吧,你的程序应该稍微修改一下

#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!.";
}

这样就能按预期工作。更多信息请点击这里。一般来说,您需要清除cin.

中的所有错误内容。

如果用户输入一个字符,它将采用字符的ASCII值,因此它不会停止。要停止循环,输入0