-
Invalid input
I'm having problems validating my input values.
To ensure only numeric input i did:
Code:
while(cin.good())
{
cout<<"Please enter a number: ";
cin>>i;
cout<<cout<<i;
}
However if i loop it and clear the buffer:
Code:
cout<<"Please enter your choice: ";
cin.seekg(0);
cin.clear();
cin>>i;
while(i<1 || i>9 || !cin.good())
{
cout<<"\aInput Error. Please make a valid choice: ";
cin.seekg(0);
cin.clear();
cin>>i;
}
In the first case if i enter any int it is expected and displayed as an int.
However in the second case
if i enter 08 instead of 8 or 09 instead of 9,
it only accepts the 0, in some cases it acceepts 010 as an octal value, and displays it at a later stage as 8.
Is there any other way i can clear the buffer.
Any help in resolving this problem will be appriciated.
-
I know Prelude has used the following code:
Code:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
And CornedBee has used this:
Code:
cin.ignore(cin.rdbuf()->in_avail());
Either one should remove whatever is in the buffer that you want to ignore. No need to use seekg.
-
The alternatives suggested by jlou dont seem to work.
I'm still using Seekg(0), and clear(), however i write the input as cin>>dec>>i;
This seems to have ended the problem.
But could you plz explain how seekg(0)and clear works, and plz suggest other alternatives,
if the use of seekg(0) is not appropriate.
-
Maybe you should post all of your code, along with sample input that shows the problem. If your code is too long, then you should make a small, but complete and compilable example that still has the problem and post that. Often times, trying to do so will show what you are doing wrong in your original program or will allow us to understand better what you are trying to do.
-
Also, forgot to mention... those examples above only work if you include the appropriate headers... more code would be helpful to diagnose the problem.
Check out this post (and the thread it came from): http://cboard.cprogramming.com/showt...243#post350243
-
>>To ensure only numeric input
Is that your requirement, to ensure that the user can only enter numerics? If so, no amount of cin'ing and ignoring will get you that (well, I suppose it could, but its a fair bit of work). By this I mean if the user enters 12345abc, the cin will read the 12345 and stop at the a, without telling your program that its done so. Whether that would be an error would be up to your design requirements.
A safer way to achieve the goal is to read the input as a string (or C or C++ style), then validate it in memory before converting it to an int or whatever.
Code:
#include <iostream>
int main(void)
{
int i;
std::cout <<"Enter number: " <<std::endl;
std::cin>>i;
std::cout <<"You entered " <<i;
return(0);
}
/*
Output
Enter number:
12345abc
You entered 12345
*/