Search code examples
c++error-handlingcastingstringstreamistringstream

Error handling casting to double with stringstream


#include <iostream>
#include <string>
#include <sstream>

int main() {
  std::istringstream iss;
  iss.str("1.23@45");
  double result;
  iss >> result;
  std::cout << result << std::endl;

  if (!iss.eof() || iss.fail()) {
    std::cout << "error occurred" << std::endl;
  }
}

output is

1.23
error occurred

Is there any better solution to check that all characters have been processed?

UPDATE

Also, I wonder if there any ways to detect out of range errors.


Solution

  • if (!iss.eof() || iss.fail())
    

    Since the string stream hasn't reached the end of the stream yet. eof() is obviously false, and this if() condition will evaluate to true.

    The results are correct: not all characters have been processed.