Check if all values were successfully read from st

2020-07-06 07:34发布

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?

标签: c++ iostream
2条回答
一夜七次
2楼-- · 2020-07-06 08:03

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).

查看更多
够拽才男人
3楼-- · 2020-07-06 08:18

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";
查看更多
登录 后发表回答