Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if all values were successfully read from std::istream

Tags:

c++

iostream

Let's say I have a file that has

100 text

If I try reading 2 numbers using ifstream, it would fail because text is not a number. Using fscanf I'll know it failed by checking its return code:

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

But when using iostream instead of stdio, how do I know it failed?

like image 864
sashoalm Avatar asked Jan 18 '13 08:01

sashoalm


2 Answers

Its actually as (if not more) simple:

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

Get used to that format, by the way. as it comes in very handy (even more-so for continuing positive progression through loops).

like image 55
WhozCraig Avatar answered Nov 02 '22 22:11

WhozCraig


If one' using GCC with -std=c++11 or -std=c++14 she may encounter:

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

Why? The C++11 standard made bool operator call explicit (ref). Thus it's necessary to use:

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

Personally I prefer below use of fail function:

std::ifstream ifs(filename);
int a, b;
ifs >> a >> b
if (ifs.fail())
  cerr << "failed";
like image 26
Paweł Szczur Avatar answered Nov 02 '22 23:11

Paweł Szczur