d ll d ll - 1 year ago 71
C++ Question

Validation of whitepsace separated integers c++

I have seen other questions on SO in regards to validation of the format of input however am looking for a more specific answer for the issue i am having.

Currently, I am required to read in 2 integer values and store them as coordinates. I have used:

cin >> x >> y

which will read the values of x & y in separated by a space.

However, any input other than a

int whitepsace int

will destroy my program. I have attempted to validate the input to ensure each value is an integer however it only applies to the first integer input.

I also need to ensure that the format of the input remains as int whitespace int so that i can consistently use the values throughout my program.

Any ideas?

Things i have tried with no luck:

  • Reading using a do - while loop w/

  • Validating using

Answer Source

Read the two values into two std::strings first. This will read in any whitespace-delimited text, without putting std::cin into a failed state.

Once the two words are read in, for each one construct a std::istringstream, use operator>> to attempt to parse it into an int. Use fail() to check whether the conversion failed, or not, and if the entire std::istringstream was consumed.

If the std::istringstream is not in failed state, and get() returned eof, then the entire word was succesfully parsed into the int.

Problem solved.

This is not, of course, the only way to do it, but is probably the most simple one, and the approach is limited to using basic C++ library classes, nothing too fancy.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download