Imagine Powers
Imagine Powers

Reputation: 13

Invalid input keeps popping out?

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.

Upvotes: 0

Views: 108

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409356

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.

Upvotes: 1

Related Questions