Check if all values ​​have been successfully read from std :: istream

Say I have a file with

100 text 

If I try to read 2 numbers using ifstream, it will fail because text not a number. Using fscanf I know that this failed by checking its return code:

 if (2 != fscanf(f, "%d %d", &a, &b)) printf("failed"); 

But when using iostream instead of stdio, how can I find out that it failed?

+6
source share
2 answers

In fact, how (if not more) is simple:

 ifstream ifs(filename); int a, b; if (!(ifs >> a >> b)) cerr << "failed"; 

We get used to this format, by the way. since it is very convenient (especially for continuing positive progression through loops).

+11
source

If "use GCC with -std=c++11 or -std=c++14 it may come -std=c++14 :

 error: cannot convert 'std::istream {aka std::basic_istream<char>}' to 'bool' 

Why? The C ++ 11 standard made the bool operator explicit ( ref ). Therefore, you must use:

 std::ifstream ifs(filename); int a, b; if (!std::static_cast<bool>(ifs >> a >> b)) cerr << "failed"; 

Personally, I prefer to use the fail function below:

 std::ifstream ifs(filename); int a, b; ifs >> a >> b if (ifs.fail()) cerr << "failed"; 
+3
source

All Articles