Member 13843522 Ответов: 2

Циклы C++: как заставить программу повторять сообщение "Ошибка" более одного раза в любое время, когда пользователь вводит неверный ввод


Всем привет,
Я почти закончил с этим заданием, но все еще испытываю проблемы с получением кода для непрерывного отображения сообщений об ошибках до тех пор, пока не будет введен правильный ввод.

Например, если пользователь вводит "4" для операции (которая должна быть между 1-3), он правильно отображает: "ваш выбор операции недействителен! Пожалуйста, попробуйте еще раз, используя 1, 2 или 3." Однако если пользователь вводит другой недопустимый номер для операции (например, 5), он не повторяет сообщение об ошибке, а просто продолжает движение вперед.

Кто-нибудь может помочь мне понять, как заставить каждое сообщение об ошибке повторяться до тех пор, пока для каждого запроса не будут введены допустимые числа или символы?

Примечание: Я очень новичок в кодировании, поэтому, пожалуйста, используйте простые объяснения или примеры в коде, если это возможно. СПАСИБО!!

Что я уже пробовал:

#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.
*/

2 Ответов

Рейтинг:
0

Jinto Jacob

привет,

проблема заключается в цикле do - while

 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);



вы можете попробовать изменить положение do непосредственно перед условием if как


       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);


в вашем коде программа ожидает ввода 2 раза в do - while (один раз перед условием if и один раз внутри условия if.)


Rick York

Подсказка пользователя должна быть в функции, я думаю. Что-то вроде этого:

int GetOperation()
{
    cout << "Choose an operation." << endl;
    cout << "Enter 1 to add, 2 to subtract, or 3 to multiply: ";
    cin >> operation;
    cout << "" << endl;
}

// then the previous loop can be written as :
   int operation = GetOperation();
   while (operation > 3 || operation < 1);
   {
       cout << "Your choice isn't valid!  Please try again." << endl;
       cout << "" << endl;
       operation = GetOperation();
   }

Rick York

Аналогично, запрос пользователю ответа должен быть функцией, которая принимает фактический ответ в качестве аргумента.

Рейтинг:
0

CPallini

Как было предложено, используйте функции, чтобы исключить дубликаты кода и сохранить вашу основную функцию аккуратной. Таким образом, поток программы легко устанавливается, например

#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++ позволяет сделать больше лаконичности:
#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;
}


[обновление]
Или
#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";
}

[/обновление]