检查是否已从std :: istream成功读取所有值

sas*_*alm 6 c++ iostream

假设我有一个文件

100 text
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用ifstream读取2个数字,它将失败,因为text它不是数字.使用fscanf我会通过检查它的返回码知道它失败了:

if (2 != fscanf(f, "%d %d", &a, &b))
    printf("failed");
Run Code Online (Sandbox Code Playgroud)

但是当使用iostream而不是stdio时,我怎么知道它失败了?

Who*_*aig 12

它实际上是(如果不是更多)简单:

ifstream ifs(filename);
int a, b;
if (!(ifs >> a >> b))
   cerr << "failed";
Run Code Online (Sandbox Code Playgroud)

顺便说一下,习惯这种格式.因为它非常方便(甚至更多 - 通过循环继续积极进展).


Paw*_*zur 6

如果使用 GCC-std=c++11-std=c++14她可能会遇到:

error: cannot convert ‘std::istream {aka std::basic_istream<char>}’ to ‘bool’
Run Code Online (Sandbox Code Playgroud)

为什么? C++11 标准使bool运算符调用显式 ( ref )。因此有必要使用:

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

我个人更喜欢以下fail功能的使用:

std::ifstream ifs(filename);
int a, b;
ifs >> a >> b
if (ifs.fail())
  cerr << "failed";
Run Code Online (Sandbox Code Playgroud)