Infinite While Loop When Input Less Than 0

Hello! I'm a bit new to C++ and very new to the forum. I was fiddling around with a while loop to practice input validation when something unexpected happened. I entered .5 for the input and the loop started running infinitely. I'm not sure why that happened. I can enter 0 and that doesn't happen. Any ideas? I thought anything less than 0 assigned to an integer evaluated to 0. If it helps, I'm using Visual Basic Express 2013.

Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  // number input program
 #include <iostream>
 using namespace std;

 int main()
 {
	 int number = 0;
	 cout << "\n\t Enter a number between 1 and 10. \n\n\t";
	 cin >> number;
	 while (number < 1 || number > 10)
	 {
		 cout << "\n\n\t You entered an invalid number, try again. \n"
			 << "\t Enter a number between 1 and 10.\n\n\t";
		 cin >> number;
	 }

	 cout << "\n\n\t Thank you! You entered " << number << ". \n\n\t";
	 return 0;
 }
I entered .5 for the input
That is the problem. '.' is not valid character for integer, so when reading operation encounters it as first symbol, reading fails. What exactly happens to number depends on standard version used, but the idea is the same: number checked in loop condition, loop is executed, input stream ties to read number (as there is still characters left in input buffer, you are not asked for more input), sees dot, fails. Repeat.
Thanks, MiiNiiPaa that makes some sense. So why wouldn't the program pause for input when I have a cin>>number statement in the loop to ask for input a second time if the first input is invalid? Also, is there a way to make the program not go into an infinite loop if something other than a number is entered?
Because entering a wrong integer value like. is not a condition in the while loop.
why wouldn't the program pause for input when I have a cin>>number statement in the loop to ask for input a second time if the first input is invalid?
Any operation on stream in failed state fails. You need to reset it state to denote that you handled (or handling) that error

is there a way to make the program not go into an infinite loop if something other than a number is entered?
There is. After input you should check for failure. then if it happened, clears stream state and discard incorrect input:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <limits>

//...

while (not (std::cin >> number) || number < 1 || number > 10) {
    std::cout << "\n\n\t You entered an invalid number, try again. \n"
                 "\t Enter a number between 1 and 10.\n\n\t";
    if(!std::cin) { //if error happened
        //Clear error state
        std::cin.clear(); 
        //Discard input
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

Thank you! That makes a lot of sense. I'll keep practicing.
Last edited on
Topic archived. No new replies allowed.