Using stringstream and an int variable in C++ to verify that input is an int
void get_english_input() {
string input = " ";
stringstream my_string(input);
int ft;
double in;
while(true) {
cout << "Enter an integer value of feet." << endl;
getline(cin, input);
my_string << input;
if(my_string >> ft)
break;
cout << "Invalid input! Please try again." << endl;
}
cout << "you entered " << ft << " as the int value for feet." << endl;
/*while(true) {
cout << "Enter a double value of inches." << endl;
getline(cin, input);
my_string << input;
break;
cout << "Invalid input! Please try again." << endl;
}
cout << "we are done entering english input" << endl;
cout << "feet = " << ft << endl;
cout << "inches = " << in <&l开发者_JAVA百科t; endl;*/
}
This code is supposed to test if the input is an integer by trying to put the contents of my_string into ft. If I enter a letter instead of an integer I get the error message "Invalid input! Please try again," which is what is supposed to happen. The problem is, after I get that message once, I will get it for every input after that, even if the next input is valid.
Someone suggested that I should use std::cin.clear(); to clear the error-flags. I tried putting it before the getline() and it did not change the problem. Was I using this incorrectly?
You could reset the error state of my_string:
my_string.clear();
my_string.ignore( /* big number of choice */ );
But I think it would be easier here just to reinitialize it every time:
while(true) {
cout << "Enter an integer value of feet." << endl;
getline(cin, input);
stringstream my_string(input);
Check out lexical_cast from Boost ...
The brute-force solution is to dump your input into a std::string, then loop over the string and check if each character is between 0 and 9.
It's not the most elegant approach. But it's simple and stupid. :-)
bool isnum(char c)
{
if(! ( c <= '9' && c >= '0'))
{
return false;
}
return true;
}
bool has_int(std::string &s)
{
for( int i = 0; i < s.length(); i++)
{
if( ! isnum(s[i])
{
return false;
}
}
return true;
}
I think
mystring >> ft
will always evaluate to be true (maybe not if mystring was empty). The operation will still work whether or not mystring actually contains a number or not.
One idea is to
size_t found=input.find_first_not_of("0123456789 ");
if (found!=string::npos)
{
cout << "Invalid input! Please try again."
}
Adapted from here.
精彩评论