循环重复而不再次提示用户
loop repeats without prompting the user again?
我从原来的长程序中得到了这段代码,尽管它看起来很简单,但它不能正确工作!我是c++语言的新手,但我知道在Java中可以这样做(不管语法如何)。
简单地说,这应该要求用户输入一个答案来回答下面的乘法(5*5),但是,它也应该检查用户是否输入了错误的输入(不是数字),不断地问用户…不知何故,它保持运行永远不接受新的输入!!
我希望得到的,不仅是一个答案,而且是一个错误的原因!
int main() {
int userAnswer;
bool isValidAnswer = true;
cout << 5 << " * " << 5 << " = ";
cin >> userAnswer;
cin.ignore();
do {
if (cin.fail()) { //user input is not an integer
cout << "Your answer is not valid! Please enter only a natural number: ";
cin >> userAnswer;
cin.ignore();
} else {
isValidAnswer = false;
}
} while (isValidAnswer);
return 0;
}
在接受新输入之前,您需要清除错误状态。在尝试再次读取输入之前,先调用cin.clear(),然后调用cin.ignore()。
我会这样做。
cout << "Enter a number: ";
cin >> number;
while(cin.fail())
{
cin.clear();
cin.ignore(1000, 'n'); //some large number of character will stop at new line
cout << "Bad Number Try Again: ";
cin >> number;
}
首先,cin.fail()不会充分检查您的答案是否是自然数,类型设置为int(也可能是负数)。
第二,你的布尔isValidAnswer
实际上是检查它是否是一个无效的答案。
第三(也是最重要的),正如另一个答案所建议的那样,您应该放入cin.clear()来清除失败状态,然后紧随其后的是cin.ignore(),它将从cin中删除失败的字符串。
第四,cin只检查字符串中是否存在int类型。您需要执行自己的字符串比较来确定整个输入是否是int(参见下面的答案,基于此答案)。
更新:
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
bool isNum(string line)
{
char* p;
strtol(line.c_str(), &p, 10);
return *p == 0;
}
int main() {
int userAnswer;
string input;
bool isInvalidAnswer = true;
cout << 5 << " * " << 5 << " = ";
while (isInvalidAnswer) {
if (!(cin >> input) || !isNum(input)) {
cout << "Answer is not a number! Please try again:n";
cin.clear();
cin.ignore();
}
else {
userAnswer = atoi(input.c_str());
if (userAnswer < 0) { //user input is not an integer
cout << "Answer is not a natural number! Please try again:n";
} else {
isInvalidAnswer = false;
}
}
}
cout << "Question answered!n";
return 0;
}
相关文章:
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- 为什么 std::cin 不提示用户输入?
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 为什么我的代码在 c++ 中无限循环.我的代码需要反复提示用户
- (显示金字塔)编写一个程序,该程序提示用户输入1到15的整数并显示金字塔
- 循环不提示用户输入(C )
- C++ 编写一个程序,提示用户以数字形式输入一个人的出生日期(投掷/接球)
- 提示用户填写链接列表
- 使用提示用户输入笛卡尔平面中某些点的x-y坐标(浮点类型)的函数
- 如何提示用户在C++中输入正确的电子邮件地址格式
- 提示用户输入,直到C++正确为止
- 安装盾,安装应用程序后,系统会提示用户安装程序
- qt检查文件中是否存在文件,如果它没有提示用户输入其位置,则将文件复制到程序工作目录
- 提示用户输入两个 3x3 int 数组并检查等效性
- 如果输入不是整数,则连续提示用户输入
- 是否可以提示用户输入并提供默认值
- 如何提示用户输入数字,直到他们选择奇数?C++
- 如何提示用户输入字符或数字
- 提示用户输入正数,并继续提示用户,直到他们输入正数 c++
- 如何使用 for 循环多次提示用户输入不同的文件名