|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||
| pdusen (4) | |||
|
I have a program that is basically a while loop meant to continue until input is -1. Inside the while loop is an input (for the user to enter -1 or any other value) and then a switch statement to execute various other functions depending on the input. If the user enters an unspecified input (for example, "e"), then they are supposed to get an "Invalid input" message and then the loop starts over. However, if I try to enter "e" for the input, it does display the message, but then it keeps reprinting "Enter paycode: " and then "Invalid input" over and over again without stopping at the cin statement like it's supposed to, going into an infinite loop I can't break out of. This has got to be something incredibly obvious for me to be having such a hard time with it. Here's the relevant part of my code:
All help is appreciated. | |||
|
|
|||
| hackitsoft (19) | |||
Problem is, that cin expecting int input, and when you insert a character, it block itself, and return 0. You must then call cin.clear() to unblock it, and using again. You also have to read unwanted input (characters).
| |||
|
|
|||
| pdusen (4) | |
|
Thanks, your modification works. However, would you mind explaining to me what some of it does? I am unclear on what (!(cin >> input)) means, what cin.clear() or cin.get() does, and why your while statement has no commands within it (it immediately terminates with a semicolon). Thank you very much! | |
|
|
|
| hackitsoft (19) | |||
|
When you use cin object (cin >> var1) it returns istream &, so you can write cin >> var1 >> var2; but if it gets invalid input (e.g. chars instead of number), it returns NULL (0), and block itself. So command if (!(cin >> input)) is true when input is ok (because it returns valid istream &), but when input is invalid, it returns NULL (== false). When cin is blocked, any attempt to use it (cin >> input) fail (it does nothing). To unblock it, and using again you have to call clear function cin.clear(). But in this moment we still have chars in input stream, and we need them get away. That does this code: while (cin.get()!= '\n'); cin.get(); reads a single char from input stream, and returns it, so we can test, if there is more chars or not (because the last is '\n'). While cycle has empty body, because command we need to do every loop if already part of the condition. It's just shorter entry of:
I hope I explain it (with my english...:-)) | |||
|
|
|||
| pdusen (4) | |
| I think I understand now, thank you very much :-) | |
|
|
|
| hackitsoft (19) | |
|
Correction: Command if (cin >> input) is true when input is ok (because it returns valid istream &), but when input is invalid, it returns NULL (== false). operator ! flips true -> false, and vice versa | |
|
|
|