Infinite loop C++ Logic errors

246 Views Asked by At

I have a simple c++ program that has a menu and allows the user to select an option with a number. There is also a block of code that ensures the input from the user is valid, however, when I for example input a letter ("s"). Instead of showing an error message and then allowing the user to input a valid response, I receive an infinite loop of the same error message. Code:

#include <iostream>
#include <algorithm>
using namespace std;

int main(){

const string PROMPT = ">> ";
int options[3] = {1, 2, 3};
int option;

// Display menu
cout << "MENU" << endl
<< "1\tAdult Tickets" << endl
<<"2\tStudent Tickets" << endl
<< "3\t2 Adults, 2 Children Tickets" << endl << endl;

// Getting option from the user and validating it
do {
// Prompt for input and get option from user
cin >> option;

// Displaying appropriate error messages
if (!isdigit(option)){
  // Invalid data type
  cout << "This is not a valid number!" << endl;
  // Not on the options menu
} else if (!(find(options, options + sizeof(options)/ sizeof(options[0]), option))){
  cout << "This option is not on the menu!" << endl;
}

} while (!isdigit(option) || !(find(options, options + sizeof(options)/ sizeof(options[0]), option)));
return 0;
}

This is an example of the output when I input "s"

This is not a valid number This is not a valid number! This is not a valid number! This is not a valid number! This is not a valid number! This is not a valid number! This is not a valid number!...

Any help will be highly appreciated and thank you in advance.

2

There are 2 best solutions below

4
On

For starters the variable option shall have the type char.

char option;

In this case you may apply the function isdigit to the entered character.

Also you are incorrectly using the find algorithm in the if statement.

The loop can look the following way.

#include <iterator>

//...

char option;
bool valid_input;

do {
    valid_input = false;

    // Prompt for input and get option from user
    cin >> option;

    // Displaying appropriate error messages
    if ( not isdigit( ( unsigned char )option)){
        // Invalid data type
        cout << "This is not a valid number!" << endl;
        // Not on the options menu
    } else if ( find( std::begin( options ), std::end( options ), option - '0') == std::end( options ){
      cout << "This option is not on the menu!" << endl;
    }
    else
    {
        valid_input = true;
    }
} while ( not valid_input );
0
On

A possible way to resolve this is to create a variable tracking validity. Like an int where 0 means it is valid while 1 or more can be invalid, then just have your loop condition check the variable.