void exercise1()
{
int number_of_lines; // Initialising variable to store the number of lines.
cout << "Enter a natural number."
<< endl;
cin >> number_of_lines;
if (number_of_lines < 0 || number_of_lines > INT_MAX) // Check if it's of type int.
{
cout << "Invalid input."
<< endl;
exercise1();
}
.....
.....
I am trying to write a condition which accepts only integer value as input. This program works if I put in values of type int without any problem. For instance if I put in value -1, it displays:
"Invalid input."
"Enter a natural number."
But if I input values which isn't an int, say an alphabet or input of type float (I do realise that the condition doesn't really do anything to take care of float types. Just trying to get over one hurdle at a time.), then the output is an infinite loop of:
"Invalid input."
"Enter a natural number."
"Invalid input."
"Enter a natural number."
"Invalid input."
"Enter a natural number."
...
...
I don't understand why it gets stuck in an infinite loop.
It is because operator >> in the line "cin >> number_of_lines;" already checked whether the input was of type int or not. You declared 'number_of_lines' to be int: no other input is acceptable.
When the input was not int, the input was rejected by cin >> and the error flag on cin was set. Attempt to read more before dealing with the error returns immediately, resulting in the endless loop.
You need to check the status of cin, for example with if(cin) { /* input was int */ } else { /*input was not int! */}. If the input as not int and you want to read more, you need to issue cin.clear() to remove the error state, and then you need to deal with the unprocessed non-integer input: either read it into a string, or simply ignore with cin.ignore(<some big number>, '\n');, if you want to be bulletproof, cin.ignore(numeric_limits<streamsize>::max(), '\n');
A couple of things about this code.
The function calls itself recursively at line 14.
That's not the ideal way to handle this situation.
A "while" loop would be better - and make the structure more obvious.
Also , the variable is declared but uninitialised at line 4: int number_of_lines;
It may happen that it contains some garbage value which is valid, and may give unexpected results.