循环或代码来处理用户输入错误直到正确为止(C++)

4

我是c++的初学者,我的任务是创建一个计算器并要求用户输入数字以进行计算。另外,我还需要创建一个代码来处理用户输入错误的情况,即程序将要求用户输入正确的数字。如何写一个处理用户输入错误的代码,使整个代码重复执行。

#include <iostream>
using namespace std;

int UI() {
  int choice;
  cout << "Enter the correspendonce number for the following options you want "
          ": \n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n\n "
          "Option: ";
  cin >> choice;
  return choice;
}

int add(int a, int b) {
  int c = a + b;
  return c;
}

int subtract(int a, int b) {
  int c = a - b;
  return c;
}

int multiply(int a, int b) {
  int c = a * b;
  return c;
}

int divide(int a, int b) {
  int c = a / b;
  return c;
}

// main function
int main() {
  int total;
  int num1, num2;
  int choice;

  choice = UI();

  if (choice == 1) {
    cout << "Input two numbers you wish to calculate for :";
    cin >> num1;
    cin >> num2;
    total = add(num1, num2);
    cout << " the total is " << total << "\n";
  } else if (choice == 2) {
    cout << "Input two numbers you wish to calculate for :";
    cin >> num1;
    cin >> num2;
    total = subtract(num1, num2);
    cout << " the total is " << total << "\n";
  } else if (choice == 3) {
    cout << "Input two numbers you wish to calculate for :";
    cin >> num1;
    cin >> num2;
    total = multiply(num1, num2);
    cout << " the total is " << total << "\n";
  } else if (choice == 4) {
    cout << "Input two numbers you wish to calculate for :";
    cin >> num1;
    cin >> num2;
    total = divide(num1, num2);
    cout << " the total is " << total << "\n";
  } else {
    cout << "Entered wrong input, please select option 1 - 5";
  }
  return 0;
}
3个回答

4
一个非常简单的方法是设置一个标志(flag):
bool done = false;
while (!done)
{
    done = true;
    int choice = UI();

    if (choice == 1) {
    
        // etc ...

    } else {
        cout << "Entered wrong input, please select option 1 - 4\n";
        done = false;
    }
}

另一个选择是将该逻辑卸载到您的输入函数中:

// Gets 1-based choice up to count.  Returns 0 on error.
int GetChoice(int count)
{
    while (cin >> choice)
    {
        if (choice >= 1 && choice <= count) {
            return choice;
        }
        cout << "Invalid choice.  Enter value from 1 to " << count << endl;
    }
    return 0;
}

然后,您只需调用:

int choice = GetChoice(4);

这样做的问题在于,如果用户输入hello或任何非整数,将会出现错误。解决这个问题最简单的方法是使用基于行的输入:
// Note, you also need to include <string> and <sstream>

int GetChoice(int count)
{
    string input;
    while (getline(cin, input))
    {
        int choice;
        istringstream iss(input);
        if (input >> choice) {
            if (choice >= 1 && choice <= count) {
                return choice;
            }
        }
        cout << "Invalid choice.  Enter value from 1 to " << count << endl;
    }
    return 0;
}

这里提供一些实用的解决方案。如果您愿意,也可以设计更华丽的东西。

非常感谢,这真的很有帮助,我的代码运行得非常顺畅! - T321

0

你可以使用goto作为基本方式,因此当用户输入1、2、3或4以外的任何数字时,她将要求再次输入数字。但是请记住,在良好的编码实践中不建议使用goto。它为您的简单问题提供了简单的解决方案。

 int UI() {
            int choice;
        x:   
            cout << "Enter the correspendonce number for the following options you want "
                ": \n1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n\n "
                "Option: ";
           
            cin >> choice;
            switch (choice)
            {
            case 1:
            case 2:
            case 3:
            case 4:
                return choice;
            default:
                cout << "Please enter 1&2&3 or 4\n";
                goto x;
            }
        }

1
加油,现在可不是1989年了... 对于这个问题使用goto是不负责任的建议。 - paddy
@paddy 我完全同意你的观点,使用goto是不好的,我在回复中已经表达了这一点。如果我们看一下问题,提问者非常基础。我的目标是为他提供一个简单的解决方案,而不会创建语法混乱并使其难以理解。否则,当然不能使用goto。 - east1000
1
你可以用这种方式来辩解,但请记住,你已经通过使用switch引入了新的语法,并推荐了一种非常不常见的解决方案。就像对于一个人冲上来想要打架,最简单的解决方法是杀了他而不是协商。这可能是一种解决方案,但绝不是常规做法,只会带来更多问题的开始。 - paddy
@paddy,感谢您分享宝贵的经验。从现在开始,我将在帮助他人时考虑您所说的话。 - east1000

0

使用以下代码替换您的代码。 简单的解决方案是将您想要重复的代码包装在while循环中, 只有当用户输入正确的输入时,循环才会结束,否则循环将重复执行,要结束循环,请使用“break”。

int main() {
  int total;
  int num1, num2;
  int choice;

while(1)
{
  choice = UI();

  if (choice == 1) {
    cout << "Input two numbers you wish to calculate for :";
    cin >> num1;
    cin >> num2;
    total = add(num1, num2);
    cout << " the total is " << total << "\n";
    break;
  } else if (choice == 2) {
    cout << "Input two numbers you wish to calculate for :";
    cin >> num1;
    cin >> num2;
    total = subtract(num1, num2);
    cout << " the total is " << total << "\n";
    break;
  } else if (choice == 3) {
    cout << "Input two numbers you wish to calculate for :";
    cin >> num1;
    cin >> num2;
    total = multiply(num1, num2);
    cout << " the total is " << total << "\n";
    break;
  } else if (choice == 4) {
    cout << "Input two numbers you wish to calculate for :";
    cin >> num1;
    cin >> num2;
    total = divide(num1, num2);
    cout << " the total is " << total << "\n";
    break;
  } else {
    cout << "Entered wrong input, please select option 1 - 5";
  }
}
  return 0;
}

1
你改了什么,为什么要这样做?一个好的回答应该解释清楚事情并帮助人们更好地理解编程语言。仅提供代码会导致盲目模仿编程。 - Lukas-T
@churill,我明白你的意思了,我已经编辑了我的答案。 - vikram jangid
1
这会引入错误的可能性,因为代码重复--对代码的任何更改必须认识到break对于防止不正确的行为是至关重要的(例如,如果添加新的选择)。虽然在这样一个微不足道的例子中很容易识别和测试,但始终要记住这一点,因为有一天你将在一个极其复杂的环境中编写代码,让行为尽可能明显是有益的。 - paddy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接