How to raise an error, if the parsed number of a C++ stdlib stream is immediatly followed by a non whitespace character?

Posted by Micha Wiedenmann on Stack Overflow See other posts from Stack Overflow or by Micha Wiedenmann
Published on 2012-11-20T16:57:55Z Indexed on 2012/11/20 16:59 UTC
Read the original article Hit count: 206

Filed under:
|

In the following example, I didn't expect, that 1.2345foo would be parsed. Since I am reading data files, it is probably better to raise an error and notify the user.

Is peek() the correct thing to do here?

#include <iostream>
#include <sstream>

int main()
{
  std::stringstream in("1.2345foo");

  double x;

  in >> x;

  if (in) {
    std::cout << "good\n";
  }
  else {
    std::cout << "bad\n";
  }
}

Output

good

© Stack Overflow or respective owner

Related posts about c++

Related posts about stream