【发布时间】:2014-10-19 19:35:09
【问题描述】:
我正在尝试创建一个简单的程序来读取范围限制,然后在这些范围之间创建一个随机数。我的程序中一切正常,但是当我运行代码时,第一条消息会打印给用户,然后我输入我的最大范围,按 Enter,光标只是移动到下一行,仍然要求输入。
我在我的代码中看不到是什么原因造成的,我很困惑。
到目前为止,这是我的代码:
#include<iostream>
#include<limits>
using std::cout;
using std::cin;
using std::endl;
int main(){
int maxRange; //to store the maximum range of our random numbers
do {
cout << "Please enter a maximum range \n";
//use clear funtion to clear the fail bit
cin.clear();
//use ignore function to avoid bad input
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while(!(cin >> maxRange)); //continue loop if cin fails
int minRange; //to store the minimum range of random numbers
do {
cout << "Please enter a minimum range \n";
//use clear funtion to clear the fail bit
cin.clear();
//use ignore function to avoid bad input
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
} while(!(cin >> minRange)); //continue loop if cin fails
int randomNumber = rand() % maxRange + minRange;
cout << "The random number that you have generated is: " << randomNumber << endl;
return 0;
}
编辑: 问题是忽略功能。这是我纠正循环的工作代码:
if(!(cin)){
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
【问题讨论】:
-
你试过在调试器中运行吗?提示:首先发生什么,读取数字,还是跳过一行?
-
是的,我已经多次通过调试器运行它。它会打印我的输入请求,然后一旦我输入输入并按下输入,它就会继续等待输入。不是clear()函数,我已经把它注释掉了,重新构建了我的项目,问题还是出现了。
-
您可能想要更彻底地测试您的“更正”代码(使用错误的输入和良好的输入)。我怀疑它是否在所有情况下都符合您的要求。
-
哇,谢谢本。我猜对我来说是艰难的一天。我现在修好了(我想)。
标签: c++ visual-studio c++11