为什么 cin in in 而没有停止获取用户输入?
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()"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
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- netcat command in c++
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- Difference in displaying cv2 Mat
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 如何在OpenSSL中从configuration.h.in获取configuration.h
- 如何在 c++ 中从".in"格式的文件中获取输入?此代码进入无限循环,但适用于".txt"文件格式
- 如何从mingw获取socket(in.h)头文件
- 为什么 cin in in 而没有停止获取用户输入?