C++ While-Loop (loop terminates along with the rest of my program)

Viewed 28

Using a while loop to check for an error in user input. I was getting an infinite loop without the return statement, how can I end the loop when the condition is met.

//QUESTION
char choice;
cout << "Would you like to give the down payment as a dollar amount($) or percent(%)" << endl;
cout << "Enter either symbol: %  or $ " << endl;
cin >> choice;

//ERROR MESSAGE LOOP 
while(choice != '$' || choice != '%') {
    cout << "ERROR: Try Again, invalid input! Enter either symbol: %  or $"<<endl;
    cin>>choice;
    if( choice == '%' || choice == '$') {
        return choice;
    }
}
1 Answers

My while loop terminates after entering % or $, but so does the rest of my program.

That's what a return statement does, it terminates the entire function, not just the loop. You need to change it to a break statement (and do something useful with the input before the break depending on the logic that you need).

Related