簡體   English   中英

檢查是否所有值均已成功從std :: istream讀取

[英]Check if all values were successfully read from std::istream

假設我有一個文件

100 text

如果我嘗試使用ifstream讀取2個數字,則會失敗,因為text不是數字。 使用fscanf,我將通過檢查其返回碼來了解它是否失敗:

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

但是,當使用iostream代替stdio時,我怎么知道它失敗了?

實際上(如果不是更多的話)很簡單:

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

順便說一下,習慣了這種格式。 因為它非常方便(甚至在循環中繼續積極發展也是如此)。

如果使用帶有-std=c++11-std=c++14 GCC,她可能會遇到:

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

為什么? C ++ 11標准使bool運算符稱為顯式( ref )。 因此有必要使用:

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

我個人更喜歡以下使用fail功能:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM