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

若如初见. 提交于 2019-12-05 06:43:43

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

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";
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!