0

Why do letters loop a cin function when the function asks for an integer?

https://code.sololearn.com/cMp7TOffT1T0/?ref=app cout<<"{1 Yes}\n{2 No}\n"; //The choices. cin>>namE; //The variable for the number choice. while(namE!=1&&namE!=2){ //The while loop that initiates if a person enters a number other than 1 and 2. cout<<"That's not valid.\n"; //Message that displays in the loop. cout<<"{Choose either 1 or 2.}\n"; //Another message. cin>>namE; //Input area again. } int gender; //Declaring the integer variable "gender". cin>>gender; //Input value of "gender". while(gender<1||gender>4){ //Loop just in case input is none of the choices (1, 2, 3, or 4). cout<<"I don't think that's valid.\n"; //Message that displays. cout<<"{Please choose again.}\n"; //Message that displays. cin>>gender; //Input value of "gender" again. } These loops keep going over and over again if anything other than an integer is input in the code. Why does it do that and what can I do to prevent this from happening? That is, what can I do so that it loops only once every single invalid input?

17th Apr 2021, 4:01 AM
Koloroj
2 Answers
+ 4
Koloroj, you changed the question. Before you were saying that the while loop is repeating forever when you change `int namE` to `char namE`. That's why I explained in terms of char and int. Anyways, the problem is, as Martin Taylor said, that if you enter an invalid input (example: "Bananas" where integer is needed), the input operation would simply fail, but the program would continue without any errors. That is why you need to check after each input if the input operation failed, and if it did, perform the necessary actions. This has been demonstrated by Martin Taylor in his answer.
17th Apr 2021, 5:22 AM
XXX
XXX - avatar
+ 3
Firstly, please save the code in a C++ code in the code playground and then link it here. It makes it easier to reference line numbers and errors/warnings. So you changed the type of `namE` to char, and then gave the second input (input into `namE`) as "1" (or "2" withtout the quotes), right? The first thing for you to know here is that char is actually an integral type, that is char character = 'A'; here, `character` actually holds 65, which is the ordinal value of the character 'A'. So when you give the input '1' (or '2') for variable `namE`, the value in `namE` will actually be 49 or 50. But as you can see on line 16, 21 and 24, you are comparing `nameE` with values like 1 and 2, which won't give error as `namE` is also actually an integer, but will always be false. So the simplest fix would be to have `namE` of type int, but if you want it to be char, you need to change the 1s ans 2s on line 16, 21 and 24 to '1's and '2's (the single quotes will make it a char which can then be compared to `namE`)
17th Apr 2021, 4:13 AM
XXX
XXX - avatar