Hello, I have a problem with the do-while loop. When user press incorrect character I would program to keep printing until the user enters a correct character, when I try to change condition infinite loop jumps in or there is no repeat it goes to next line. Can someone explain what I need to do correct my logic condition in the loop. Thanks
showType = 'x';
do {
switch (showType) {
case'M': case'm':
cout << "Alice in Woderland\n";
break;
case'E': case'e':
cout << "The Book of the Dead\n";
break;
default:
cout << "Invalid Choice";
}
} while(!(showType == 'M' || showType == 'm'||
showType == 'E' || showType == 'e'));
We set the value of showType on the first line, before the loop.
Nothing inside the loop changes the value of showType, does it?
If showType does not change, then the result of condition cannot change.
Thank you for a suggestion about tolower. For some reason, I'm still getting an infinite loop with default statement: "Invalid Choice", when I press other characters than m or e. The value of showType doesn't change.
When we arrive to the loop, the cond has been set.
* If it is false, then the loop executes exactly once and ends.
* If it is true, the loop repeats forever, because the cond stays true.
The solution is to change the cond inside the loop.
If the idea is to keep asking showType from the user until either 'm' or 'e' is got, then you have to ask from the user inside the loop.
There is one more thing: what if the input operation fails? One has to check for that.
1 2 3
do {
std::cin >> cond; // cond can change on every iteration
} while ( std::cin && cond ); // repeat loop if input was successful and cond is true