作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我希望我的代码只输入整数。下面的代码正确地完成了它的工作,并在没有使用整数的情况下要求用户输入。但是,添加代码后:
while ( ! ( cin >> x ))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter a number: ";
}
进入下面的代码,只有当我首先输入一个非整数时它才有效。否则,如果我先输入一个 int,程序不会继续执行下一条语句,也不会执行任何操作。我的推理是,如果 x = int 那么 while 循环将不会启动。那么为什么添加代码会弄乱剩余的代码。
#include <iostream>
#include <limits>
using namespace std;
main ()
{
cout << "Enter a number: ";
int x, y;
cin >> x;
while ( ! ( cin >> x ))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter a number: ";
}
cout << "Enter a number: ";
cin >> y;
最佳答案
问题是您从 cin
中读取的次数太多了 1 次:
int x, y;
cin >> x; // <-- reads an int, without validation!
while ( ! ( cin >> x )) { // <-- reads ANOTHER int!
在进入 while
循环之前,您需要去掉第一次读取。让循环单独进行读取:
#include <iostream>
#include <limits>
using namespace std;
main () {
int x, y;
// <-- NO READ HERE!
cout << "Enter a number: ";
while (!(cin >> x)) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Enter a number: ";
}
// same as above, for y ...
}
或者,使用 do..while
循环代替:
#include <iostream>
#include <limits>
using namespace std;
main () {
int x, y;
// <-- NO READ HERE!
do {
cout << "Enter a number: ";
if (cin >> x) break;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
while (true);
// same as above, for y ...
}
关于c++ - 如何在不中断剩余代码的情况下仅 cin C++ 中的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49345728/
我是一名优秀的程序员,十分优秀!