-1

Novice trying to self teach himself C++ here.

Here is the code for reference:

#include <iostream>
void function1(int);
void function2(int);
void function3(int);

using namespace std;
int main() {
    int input = 0;
    while (input != 4){
      cout << "Prompt" << endl;
      cin >> input;
      switch(input) {
           case 1:
              function1(input);
              break;
           case 2:
              function2(input);
              break;
           case 3:
              function3(input);
              break;
           case 4:
              cout << "Program terminated." << endl;
              return 0;
              break;
           default:
              cout << "Invalid input." << endl;
              input = 4; // Exits the while-loop.
              break;

       }
   }
}

void function1(int a) {
    int prompt;
    cout << "Prompt again" << endl;
    cin >> prompt;
    if (!cin){
        cout << "Input is not a number." << endl;
        return;
    }
}

void function2(int a) {
}

void function3(int a) {
}

What I'm trying to do is make a function1 that detects if a specific input was a string or a char instead of an integer, and then say that it is not a number, then go back to the switch case statements. Once it detects this though, the statements in the while loop go on forever and completely bypass the cin prompts! I understand from reading other people's questions that the infinite looping might have something to do with using 'int' in a header and inputting a string when an integral is expected, but I don't understand why the code doesn't stop when the cin is prompted or how to bypass it. Any help?

Jonathan
  • 3
  • 1

1 Answers1

-1
if (!cin){
    cout << "Input is not a number." << endl;
    return;
}

When cin<< reads a bad input, its flags are set to an error state. The error state needs to be cleared by resetting the flags to zero, which is done using cin.clear(). Change your if-statement to include the cin.clear() statement:

if (!cin){
    cout << "Input is not a number." << endl;
    cin.clear(); // <-- Add this line
    return;
}

When you enter invalid input for cin <<, the error flags of cin<< are set to 1 (true). That is why we use cin.clear(); so that the error flags are reset to zero, and cin<< can accept new input.

BusyProgrammer
  • 2,783
  • 5
  • 18
  • 31