【问题标题】:How to ignore invalid input when reading file?读取文件时如何忽略无效输入?
【发布时间】:2020-11-29 14:55:13
【问题描述】:

进行一项要求在忽略无效输入的情况下查找文件中数字总和的练习,即“熊:17 只大象 9 结束”将输出 26。现在在读取文件时,输入一旦遇到错误就会终止,我一直在试图找到解决方法。我确定问题出在 read_file 的 ist.fail() 部分。

void read_file(string iname, vector<int>& result) {
  ifstream ist {iname}; // ist reads from the file named iname
  if (!ist) error("can't open input file ",iname);

  for (int temp; ist >> temp; ) 
    result.push_back(temp);
  
  if (ist.fail()) {
    ist.clear(ios_base::failbit);
  }
}

void write_file(string& oname, string& input1, const vector<int>& result) {
  ofstream ost {oname}; // ost writes to a file named oname
  if (!ost) error("can't open output file ",oname);

  double sum = 0;
  for (int i=0; i<result.size(); ++i)
    sum += result[i];
  ost << sum;
}

int main()
{ 
  string input = "a.txt";
  string output = "b.txt";
  vector<int> result;

  read_file(input, result);
  write_file(output, input, result);
}

【问题讨论】:

  • 您的怀疑是正确的:“问题出在 read_file 的 ist.fail() 部分”,确实。因为,即使 ist 处于失败状态,并且这部分代码将其清除,也没有任何区别,因为代码无论如何都会从函数返回,从而破坏输入流和打开的文件。你能解释一下你在完全销毁输入流之前明确清除输入流状态的理由吗?
  • 实际上稍微修改了ist.fail(),使其后面是ist.clear()和ist.ignore(std::numeric_limits<:streamsize>::max(), '\n ')。所以我清除了错误状态,然后忽略了流中的数据。还是一样的结果。
  • 为什么你会期待任何不同的结果?无论如何,代码仍然从函数返回。您忘记了计算机编程的黄金法则:“您的计算机始终完全按照您的要求执行操作,而不是您希望它执行的操作”。您告诉您的计算机:在完成所有这些之后,清除状态,忽略输入,无论如何:从函数返回并停止从文件中读取。您的计算机只是按照您的指示进行操作。如果你想让你的电脑做其他事情,你必须告诉你的电脑你的电脑应该做什么。

标签: c++ file c++11 vector input


【解决方案1】:

将每个空格分隔的标记读入字符串,尝试将其转换为整数。如果失败则跳过token,否则将其插入向量中:

#include <sstream>

void read_file(string iname, vector<int>& result) {
  ifstream ist{iname};  // ist reads from the file named iname
  if (!ist) error("can't open input file ", iname);

  istringstream iss;
  for (string token; ist >> token; iss.clear()) {
    iss.str(token);
    int val;
    if (iss >> val) {
      result.push_back(val);
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 2016-04-18
    相关资源
    最近更新 更多