Okay, I have a while loop with a for loop that waits till the user inputs one of two acceptable answers y(yes), and n(no). The loop is correct and all, but when the user inputs more than one character the loop goes through multiple times, and writes out the initial question several times. My question is, how do I make my program catch that the whole string the user inputs is wrong instead of checking every single character?
bool x= true;
char lExt;
while ( x = true )
{
std::cout << "Do you have any questions before we continue?[y/n]" << std::endl;
std::cin >> lExt;
if ( lExt == 'y' )
{
std::cout << "What would you like to know more about?" << std::endl;
aboutarra();
break;
}
else if ( lExt == 'n' )
{
std::cout << "Okay, lets continue!" << std::endl;
break;
}
Also, you're using the assignment operator in your while loop, use == instead of =. You could also just write while (x). On the other hand, you never update x, so you could just write while (true).
if(IExt != 'Y' && IExt != 'N')
{
//Error Message like "Invalid input"
//Go back
}
if(IExt != 'Y' && IExt != 'N')
{
//Error Message like "Invalid input"
//Go back
}
I find this use of != to test for invalid input counter intuitive and error prone. The OP's code has some problems but i like the use of the boolean in the while expression. I prefer the OP's if statement rather than this != code.
The OP needs to update the value of x before the end of the loop. Also he doesn't collect any input after one of the questions.
Thank you so much! I totally forgot about the != operator, and after a while of playing around with it I got it to work! I know this is off topic, but do any of you know how to make a suitable "Press any key to continue..." function other than
system("PAUSE"); // I read that this is a very bad way of doing it.
or
cin.get(); // When I do it this way, i have to press a key in twice
cin.ignore(); // for the program to move on.
Thank you so much! I totally forgot about the != operator, and after a while of playing around with it I got it to work!
I am not sure whether you got it to work by using the != or not. I am saying that doing it that way isn't good.
Consider this function, which decides whether a char is an operator or not. You could have a similar function that decides if the input is good or not.
Okay, Ive got it to go through the switch statement, but my problem is the default option. when I type in say "234" it just quits the program. Ill have to work on it a bit.