C ++循环:如何让程序重复“错误”用户输入无效输入时不止一次发送消息 [英] C++ loops: how to get program to repeat "error" message more than once anytime user enters invalid input

查看:80
本文介绍了C ++循环:如何让程序重复“错误”用户输入无效输入时不止一次发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我几乎完成了这项任务,但仍然无法让代码连续显示错误消息,直到输入正确的输入。



例如,如果用户输入4进行操作(应该在1-3之间),它会正确显示:您的操作选择无效!请再试一次,使用1,2或3。但是,如果用户为操作输入了另一个无效号码(例如5),则不会重复该错误消息,而是继续前进。



任何人都能够帮我弄清楚如何重复每个错误信息,直到为每个提示输入有效的数字或字符?



注意:我是对编码很新,所以如果可能的话,请在代码中使用简单的解释或示例。谢谢!!



我的尝试:



Hello all,
I'm ALMOST done with this assignment, but still having trouble getting the code to display the error messages continuously until the correct input is entered.

For example, if the user enters "4" for operation (which should be between 1-3), it correctly displays: "Your operation choice isn't valid! Please try again, using 1, 2, or 3." However, if the user enters another invalid number for the operation (such as 5), it doesn't repeat the error message, but just continues forward.

Anyone able to help me figure out how to get each error message to repeat until valid numbers or characters are entered for each prompt?

Note: I am very new to coding, so please use simple explanations or examples in code, if possible. THANK YOU!!

What I have tried:

#include <iostream>
#include <cstdio>
#include <time.h>
#include <stdlib.h>
using namespace std;

int main()
{
    int operation, num3, guess, num1, num2, temp;
    char play;
    srand(time(0));

    do
    {
      num1 = rand() % 10;
      num2 = rand() % 10;

      if (num1 < num2)
      {
          temp = num1;
          num1 = num2;
          num2 = temp;
      }
        do
        {
            cout << "Choose an operation." << endl;
            cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " <<
endl;
            cout << "" << endl;
            cin >> operation;
            cout << "" << endl;

            if (operation > 3 || operation < 1)
            {
                cout << "Your operation choice isn't valid!  Please try
again, using 1, 2, or 3." << endl;
                cout << "" << endl;
                cout << "Choose an operation." << endl;
                cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: "
<< endl;
                cout << "" << endl;
                cin >> operation;
                cout << "" << endl;
            }
        }
        while (operation > 3 || operation < 1);

        switch(operation)
        {
            case 1:
            cout << "You chose addition." << endl;
            num3 = num1 + num2;
            cout << "" << endl;
            cout << "What is " <<  num1 << " + " << num2 << " ?: " << endl;
            cout << "" << endl;
            cin >> guess;
            cout << "" << endl;

                if (guess != num3)
                    {
                    cout << "That is incorrect. Please try again." << endl;
                    cout << "" << endl;
                    cout << "What is " <<  num1 << " + " << num2 << " ?: "
<< endl;
                    cout << "" << endl;
                    cin >> guess;
                    cout << "" << endl;
                    }

                else if (guess == num3)
                    {
                    cout << "That is correct!" << endl;
                    cout << "" << endl;
                    }
            break;

            case 2:
                cout << "You chose subtraction." << endl;
                num3 = num1 - num2;
                cout << "What is " <<  num1 << " - " << num2 << " ?: " <<
endl;
                cout << "" << endl;
                cin >> guess;
                cout << "" << endl;

                    if (guess != num3)
                        {
                        cout << "That is incorrect. Please try again." <<
endl;
                        cout << "" << endl;
                        cout << "What is " <<  num1 << " - " << num2 << " ?:
" << endl;
                        cout << "" << endl;
                        cin >> guess;
                        }

                    else if (guess == num3)
                        {
                        cout << "That is correct!" << endl;
                        cout << "" << endl;
                        }
                break;

            case 3:
                cout << "You chose multiplication." << endl;
                num3 = num1 * num2;
                cout << "What is " <<  num1 << " * " << num2 << " ?: " <<
endl;
                cout << "" << endl;
                cin >> guess;
                cout << "" << endl;

                    if (guess != num3)
                        {
                        cout << "That is incorrect. Please try again." <<
endl;
                        cout << "" << endl;
                        cout << "What is " <<  num1 << " * " << num2 << " ?:
" << endl;
                        cout << "" << endl;
                        cin >> guess;
                        }

                    else if (guess == num3)
                        {
                        cout << "That is correct!" << endl;
                        cout << "" << endl;
                        }
            break;
        }

        do
        {
             cout << "Would you like to play again? Press Y for yes or Q for
quit" << endl;
             cout << "" << endl;
             cin >> play;

           if (play != 'Y' && play != 'Q')

            {
                cout << "That is not a valid choice. Please choose Y for yes
or Q to quit. " << endl;
                cout << "" << endl;
            }

        }

        while(play !='Y' && play !='Q');

        if (play == 'Y')
        {
        cout << "Thank you for playing! Let's play again!" << endl;
        cout << "" << endl;
        }

        else
        {
        cout << "Thank you for playing! See you next time!" << endl;
        cout << "" << endl;
        }

     }
     while(play=='Y');
return 0;
}
/*Sample Run:
Choose an operation.
Enter 1 to add, 2 to subtract, or 3 to multiply:

3

You chose multiplication.
What is 4 * 1 ?:

4

That is correct!

Would you like to play again? Press Y for yes or Q for quit

Y
Thank you for playing! Let's play again!

Choose an operation.
Enter 1 to add, 2 to subtract, or 3 to multiply:

1

You chose addition.

What is 6 + 1 ?:

7

That is correct!

Would you like to play again? Press Y for yes or Q for quit

Y
Thank you for playing! Let's play again!

Choose an operation.
Enter 1 to add, 2 to subtract, or 3 to multiply:

2

You chose subtraction.
What is 5 - 0 ?:

5

That is correct!

Would you like to play again? Press Y for yes or Q for quit

Y
Thank you for playing! Let's play again!

Choose an operation.
Enter 1 to add, 2 to subtract, or 3 to multiply:

1

You chose addition.

What is 7 + 1 ?:

9

That is incorrect. Please try again.

What is 7 + 1 ?:

10

Would you like to play again? Press Y for yes or Q for quit

Y
Thank you for playing! Let's play again!

Choose an operation.
Enter 1 to add, 2 to subtract, or 3 to multiply:

2

You chose subtraction.
What is 7 - 3 ?:

5

That is incorrect. Please try again.

What is 7 - 3 ?:

6
Would you like to play again? Press Y for yes or Q for quit

Q
Thank you for playing! See you next time!


Process returned 0 (0x0)   execution time : 43.057 s
Press any key to continue.
*/

推荐答案

hi,



问题是do-while循环





the problem is the do- while loop

 do
        {
            cout << "Choose an operation." << endl;
            cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " <<
endl;
            cout << "" << endl;
            cin >> operation;
            cout << "" << endl;

            if (operation > 3 || operation < 1)
            {
                cout << "Your operation choice isn't valid!  Please try
again, using 1, 2, or 3." << endl;
                cout << "" << endl;
                cout << "Choose an operation." << endl;
                cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: "
<< endl;
                cout << "" << endl;
                cin >> operation;
                cout << "" << endl;
            }
        }
        while (operation > 3 || operation < 1);







您可以尝试在if条件之前更改do的位置








you can try changing the position of do just before the if condition as


       cout << "Choose an operation." << endl;
            cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: " <<
endl;
            cout << "" << endl;
            cin >> operation;
            cout << "" << endl;

do
        {
      
            if (operation > 3 || operation < 1)
            {
                cout << "Your operation choice isn't valid!  Please try
again, using 1, 2, or 3." << endl;
                cout << "" << endl;
                cout << "Choose an operation." << endl;
                cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: "
<< endl;
                cout << "" << endl;
                cin >> operation;
                cout << "" << endl;
            }
        }
        while (operation > 3 || operation < 1);





在你的代码中,程序在do - while中等待输入2次(如果是条件则一次,如果是条件则是一次。)



in your code the program is waiting for the input 2 times in the do - while (one before if condition and one inside if condition.)


如建议的那样,使用函数来分解重复代码并保持您的主要功能整洁。通过这种方式,程序流程很容易解决,例如



As suggested, use functions to factor out duplicate code and keep your main function neat. This way the program flow is easily settled, e.g.

#include <iostream>
#include <cstdlib>
#include <string>
#include <cassert>
using namespace std;

struct Operation
{
  string name;
  string symbol;
};

enum
{
  eAdd = 0,
  eSub,
  eMul,
  eOperations
};

int computeResult(size_t choice, int x, int y);
size_t askOperation(const Operation op_array[], size_t size);
int askGuess(const Operation & op, int x, int y);

int main()
{
  srand(time(0));

  Operation op_array[eOperations] = { { "addition", "+" }, { "subtraction", "-"}, {"multiplication", "*"}};

  while (true)
  {
    size_t choice = askOperation( op_array, eOperations );
    if ( choice >= eOperations) break;
    int a = rand() % 10;
    int b = rand() % 10;
    if ( a < b ) swap(a,b);
    int result = computeResult(choice, a, b);
    int guess = askGuess( op_array[choice], a, b);
    cout << "your answer is " << ( guess == result ? "correct" : "incorrect") << endl << endl;

  }
  cout << "see you next time" << endl;
} // <- main

int computeResult(size_t choice, int x, int y)
{
  int result = -1;
  switch( choice)
  {
  case eAdd:
    result = x + y;
    break;
  case eSub:
    result = x - y;
    break;
  case eMul:
    result = x * y;
    break;
  default:
    assert(false);
  }
  return result;
}

size_t askOperation(const Operation op_array[], size_t size)
{
  cout << "choose an operation. " << endl << "enter";
  for (size_t n=0; n<size; ++n)
    cout << ", " << (n+1) << " for " << op_array[n].name;
  cout << " (any other value to exit): " << endl;
  int choice;
  cin >> choice;
  return (choice-1);
}

int askGuess(const Operation & op, int x, int y)
{
  cout << "you choose " << op.name << endl;
  cout << "what is " << x << " " << op.symbol <<  " " << y << " ?" << endl;
  int result;
  cin >> result;
  return result;
}





现代 C ++ 允许更简洁:



Modern C++ allowes more concision:

#include <iostream>
#include <utility>
#include <cstdlib>
#include <string>
#include <array>

using namespace std;

using Function = int (int, int);

struct Operation
{
  string symbol;
  string name;
  Function * fun;
};

size_t askOperation(const array<Operation, 3> & oper_array);
int askGuess(const Operation & oper, int x, int y);

int main()
{
  srand(time(0));

  array<Operation, 3> oper_array =
  {{
    { "+", "addition", [](int x, int y) { return x+y;} },
    { "-", "subtraction", [](int x, int y) { return x-y;} },
    { "*", "multiplication", [](int x, int y) { return x*y;}}
  }};

  while (true)
  {
    auto choice = askOperation( oper_array );
    if ( choice >= oper_array.size()) break;
    int a = rand() % 10;
    int b = rand() % 10;
    if ( a < b ) swap(a,b);
    Operation & oper = oper_array[choice];
    int result = oper.fun( a, b );
    int guess = askGuess( oper, a, b);
    cout << "your answer is " << ( guess == result ? "correct" : "incorrect") << endl;

  }
  cout << "see you next time" << endl;
}// <- main

size_t askOperation(const array<Operation, 3> & oper_array)
{
  cout << "choose an operation. " << endl << "enter";
  for (size_t n=0; n<oper_array.size(); ++n)
    cout << ", " << (n+1) << " for " << oper_array[n].name;
  cout << " (any other value to exit): " << endl;
  int choice;
  cin >> choice;
  return (choice-1);
}
int askGuess(const Operation & oper, int x, int y)
{
  cout << "you choose " << oper.name << endl;
  cout << "what is " << x << " " << oper.symbol <<  " " << y << " ?" << endl;
  int result;
  cin >> result;
  return result;
}





[update]





[update]
Or

#include <iostream>
#include <functional>
#include <map>
#include <cstdlib>
using namespace std;

int main()
{
  srand(time(0));

  using Operation = tuple< string, char , function < int (int, int) > >;

  map < int, Operation > m = {
    {1, {"addition", '+', plus<int>() }},
    {2, {"subtraction", '-', minus<int>() }},
    {3, {"multiplication", '*', multiplies<int>() }},
    };

  while (true)
  {
    cout << "\nenter choice:\n";
    for (const auto & [i, oper] : m)
      cout << '\t' << i << " " << get<0>(oper) << '\n';
    cout << "any other value to exit\n";
    int choice;
    cin >> choice;
    auto it = m.find(choice);
    if ( it == m.end()) break;

    int a = rand()%10;
    int b = rand()%10;
    if ( a < b ) swap(a,b);

    const auto & [name, symbol, fun] = it->second;

    cout << "you choose " << name << "\n";
    cout << "what is " << a <<  " " << symbol << " " << b << " ?\n";
    int guess;
    cin >> guess;
    cout << "your guess is " << (fun(a,b) == guess ? "correct\n" :  "incorrect\n");
  }
  cout << "see you next time\n";
}



[/ update]


这篇关于C ++循环:如何让程序重复“错误”用户输入无效输入时不止一次发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆