1

I want to validate the input by user to make sure it's an integer (fully). I've tried a few methods, like !cin, but none of them work properly..

Most of methods fail to validate input like this:

32tgf

When there is a number first and then letters, it doesn't fail, but it takes it as valid entry..

Note: It's a project for college and it's specified that the variable should be of type int.

user2699298
  • 1,368
  • 3
  • 15
  • 32
  • 1
    You say you've tried methods... where is the code? How were you unable to find any of the dozens of good existing answers here on StackOverflow? – Ben Voigt Jan 03 '14 at 17:57
  • What syntax? Leading '+|-' sign? Does it handle hexadecimal, etc? – Brett Hale Jan 03 '14 at 18:40

1 Answers1

3

Read into a string, then use e.g. std::stoi or std::strtol to both convert to an integer and validate the input.

Or read into a string, put that string in a std::istringstream which you use to extract the integer. Then check if there's anything more in the istringstream.

I'd recommend the first method though.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550