0

I don't know if it is a logic error or code error. I created a menu and within menu there's bunch of if statement and if user input doesn't satisfy the if or else if statements it goes to else statement. I have this problem when I input letters it means Invalid but it keeps printing out Invalid input over and over it doesn't go back in the previous menu. How do I fix that error?

I have tried deleting the system("CLS") but it doesn't work.

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

 int main()
{

while (true)
{
    int choice;
    cout<<"Menu\n\n\n";
    cout<<"1. Fruits\n";
    cout<<"2. Vegetables\n";
    cout<<"3. Exit\n\n";
    cout<<"Choice: ";
    cin>>choice;

if(choice == 1){
    system ("CLS");

    system ("PAUSE");
    system ("CLS");
}

else if(choice == 2){
    system ("CLS");

    system ("PAUSE");
    system ("CLS");
}

else if(choice == 3){
    return 0;
}

else if(choice > 3 || choice < 1 ){
    system ("CLS");
    cout<<"Invalid Input\n\n";
    system ("PAUSE");
    system ("CLS");
}

else{
    system ("CLS");
    cout<<"Invalid Input\n\n";
    system ("PAUSE");
}
}
}

It should print out only one Invalid input then it goes back to the menu.

  • 1
    It's an error of your understanding of how `cin` works. Specifically what happens on invalid input. Looking for a good duplicate, but it's hard to search for. – john Apr 01 '19 at 09:03
  • You can rewrite this better using switch case as well. – Ali Ben Zarrouk Apr 01 '19 at 09:05
  • can you show me how? I know switch case but don't know how to apply in this situation. – Imagine Powers Apr 01 '19 at 09:09
  • @ImaginePowers `switch` won't help with non-integer input. But apart from that just `switch (choice) { case 1: ... break; case 2: ... break; case 3: ... break; default: ... break; }`. – john Apr 01 '19 at 09:11
  • Possible duplicate https://stackoverflow.com/questions/19696442/how-to-catch-invalid-input-in-c. This is the try and recover method, I still prefer what 'dude' suggests though. – john Apr 01 '19 at 09:21

1 Answers1

1

If you enter something that can't be parsed as an integer, then that will be left in the input buffer. So the next time you attempt to read input it will read the exact same invalid input, over and over again.

One possible solution is to use std::getline to read a full line into a std::string, and then use e.g. std::stoi to convert the string to an integer.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • In general this is the best solution. If you are trying to deal with non-integer input then don't try and read an integer and then recover. Don't make any assumptions at all about your input. – john Apr 01 '19 at 09:09