Thank you both for the quick replies.
I found an article in another site about this problem. I will not include the link since I don't know if it is allowed, but I here's the part that helped me
Reading in numbers directly is problematic
* If std::cin is presented with input it cannot process, std::cin goes into a "fail" state
* The input it cannot process is left on the input stream.
* All input will be ignored by std::cin until the "fail" state is cleared: std::cin.clear()
* A routine that reads a number directly should:
1. Read in the number
2. Check to see that the input stream is still valid
3. If the input stream is not good (!std::cin)
1. Call std::cin.clear() to take the stream out of the "fail" state.
2. Remove from the stream the input that caused the problem: std::cin.ignore(...)
3. Get the input again if appropriate or otherwise handle the error
Inputing numbers directly, version 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include<limits> //for numeric_limits
float fl;
int bad_input;
do{
bad_input=0;
std::cin >> fl;
if(!std::cin)
{
bad_input=1;
std::cin.clear();
std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}
}while(bad_input);
|
Inputing numbers directly, version 2:
1 2 3 4 5 6 7
|
#include<limits> //for numeric_limits
float fl;
while(!(std::cin >> fl))
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}
|
A note on limits. If your compiler doesn't support std::numeric_limits<streamsize>::max(), an alternative is to use the c-style method for determining the maximum integer allowed:
1 2 3
|
#include<climits>
...
std::cin.ignore(INT_MAX, '\n');
|
PS: mtweeman : Your solution was also included in the article. Thanks.
PS2: wtf:
Please restart program and don't be stupid.
. I definitely like your style.