Gordon Zheng
Gordon Zheng

Reputation: 509

How can you tell if a stream extraction to a variable failed?

I am extracting data from a string stream into a string and a double:

std::string word;
double num;
std::istringstream stream("hello x");

stream >> word >> num;

std::cout << word;
std::cout << num;

Is it possible to tell if the second token, "x" was successfully parsed into an int?

In this case, it would obviously not, and the value of x is 0.

Upvotes: 1

Views: 307

Answers (1)

nkryptic
nkryptic

Reputation: 86

The extraction operator (>>) will return true or false on whether the extraction was successful.

if (stream >> num)
  cout << "success\n";
else
  cout << "failed\n";

In addition, you will likely see the failbit set on the istringstream object

if (stream.fail())
  cout << "failbit is set\n";

Upvotes: 6

Related Questions