Why my code runs infinite time when i entered non integer type in c++ [duplicate]

Solution 1:

The problem is that when you call

cin>>mainOption; // mainOption is an int

but the user does not enter an int, cin leaves the input buffer in the old state. Unless your code consumes the invalid portion of the input, the incorrect value entered by the end user would remain in the buffer, causing infinite repetitions.

Here is how you fix this:

} else {
    cout<<"Please Enter Valid Input. "<<endl;
    cin.clear(); // Clear the error state
    string discard;
    getline(cin, discard); // Read and discard the next line
    // option remains true, so the loop continues
}

Note that I also removed the recursion, because your while loop is good enough to handle the task at hand.