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

一笑奈何 提交于 2019-12-07 02:27:19

问题


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?


回答1:


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




回答2:


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";


来源:https://stackoverflow.com/questions/14394724/check-if-all-values-were-successfully-read-from-stdistream

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