0

I'm trying to read input that has ints and strings, in this case an expression like 1 2 +. I've been trying to use cin.fail() to determine if the input is numeric.

int x;
string s;
if (cin >> x){
  // do something
} else {
  cin >> s;
  //do something else
}

I realized this skips input but can't figure out how to solve the problem. Would I have to read everything as a string then check and convert to int? I would like to find a better solution if possible and would be very grateful for any assistance.

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
  • This should work fine. What's not working? – Eli Sadoff Nov 14 '16 at 20:56
  • 1
    @EliSadoff: Op would need to restore the state of the stream for this to work. – AndyG Nov 14 '16 at 20:58
  • If I try passing in 1 2 + 3 * it skips the + and reads 3 as a string. – user2975120 Nov 14 '16 at 20:58
  • @AndyG is right. You need to run `cin.clear(istream::failbit);` in the `else` block. – Eli Sadoff Nov 14 '16 at 20:59
  • @AndyG: How would I go about doing that? I'm new to c++. – user2975120 Nov 14 '16 at 20:59
  • 1
    @EliSadoff: That's not exactly what I mean. When you've read input from the stream, it's no longer there. If it fails, it's still not there. Yes, resetting the flag will help, but you also need to move the stream position back to where it was before the read. There are other posts on SO about this. I'll dig one up. – AndyG Nov 14 '16 at 21:00
  • 3
    You should probably not do this by reading individual items. Read a whole line, split it into tokens, and then loop over those to see if they look like a number or operator. – Barmar Nov 14 '16 at 21:04
  • It's surprisingly hard to find a dup, although I know I've seen these around. Anyway, Barmar is right. Here's a good candidate for a dup, and at the very least something useful to look at: http://stackoverflow.com/a/26151374/27678 – AndyG Nov 14 '16 at 21:08
  • The marked duplicate is wrong. OP: If you're only receiving operators and integers, you can read a string and then test to see if it's an int, and then otherwise assume an operator. [std::stoi](http://en.cppreference.com/w/cpp/string/basic_string/stol) will perform conversion of the string to your desired integer after you've validated the input. Edit: Example: http://coliru.stacked-crooked.com/a/eef7f61be3fcec62 – AndyG Nov 14 '16 at 21:28

0 Answers0