该程序打印指定范围内指定数量的数字。但是,当我输入一个字符时,它只会无限循环我在其中执行的 do-while 循环。例如:如果我在“输入最大数字”cin 中输入一个字符,它只会无休止地发送垃圾邮件“输入最大数字”,它只是跳过cin 并循环 cout (其他 2 个 do-while 也是如此。有人知道为什么吗?
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int roll(int mini, int maxi)
{
int v = maxi - mini;
int x = mini + (rand() % (v+1));
return x;
}
void caller()
{
int a;
int b;
int c;
do {
cout << "Enter minimum number" << endl;
cin.clear();
cin >> a;
} while (cin.fail());
do {
cout << "Enter maximum number" << endl;
cin.clear();
cin >> b;
} while (cin.fail() || a > b);
do {
cout << "How many rolls?" << endl;
cin.clear();
cin >> c;
} while (cin.fail());
for (int i = 0; i < c; i++)
cout << roll(a, b) << endl;
}
int main()
{
srand (time(NULL));
caller();
return 0;
}
我宁愿不使用istream::fail()
用于循环控制。看为什么循环条件内的 iostream::eof 被认为是错误的?对于类似的问题。
相反,我依赖于返回值istream::operator >>
.
我还使用以下函数来重置标志并清除输入流上的输入:
void flush_stream(std::istream& stream)
{
stream.clear();
stream.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
See 如何刷新 cin 缓冲区?了解更多相关信息。
所以我会对你的输入检查进行编码:
int get_valid_number(const std::string& prompt)
{
int number = 0;
bool valid = false;
while (!valid)
{
std::cout << prompt << std::endl;
if (std::cin >> number)
{
valid = true;
}
flush_stream(std::cin);
}
return number;
}
希望将其提取到函数中的好处是显而易见的。看到它运行.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)