循环重复而不再次提示用户

loop repeats without prompting the user again?

本文关键字:提示 用户 不再 循环      更新时间:2023-10-16

我从原来的长程序中得到了这段代码,尽管它看起来很简单,但它不能正确工作!我是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;
}