Check if a field value is a float or int

How can I check if a user inserted value is a float number (or integer) as I'm expecting? Thank you.
You can only check if it's an integer, since all integers are also floats.

1
2
3
4
5
6
7
int a;
std::string line;
std::getline(std::cin,line);
std::stringstream stream;
if (!(stream >>a)){
    //it wasn't an integer
}
You can also check the input string for a decimal as well. The check should occur after the stream is assigned to the variable 'a' so that you can verify that it is in fact a number.

1
2
3
4
5
6
7
8
int a;
std::string line;
std::getline(std::cin,line);
std::stringstream stream(line);
if ( !(stream >> a) || line.find('.')!=std::string::npos )
{
   // Not an integer
}
Last edited on
User had similar problem here:
http://www.cplusplus.com/forum/beginner/13044/page1.html

And my (fancy) solution for him:
http://www.cplusplus.com/forum/beginner/13044/page1.html#msg62827

Note the commentary on how it works -- you don't need to use the templates or other fancy things. Just the stringstream and a check on eof().

Good luck!
Topic archived. No new replies allowed.