gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:36:05 27 4
gpt4 key购买 nike

我现在开始学习 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”之类的操作。

最佳答案

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

#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 中的所有错误内容。

关于c++ - 为什么 cin inside while 不停地获取用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33168544/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com