c++ - 读取文件时如何忽略无效输入?

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

进行一个要求在不考虑无效输入的情况下查找文件总数的练习,即“熊: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);
}

最佳答案

将每个以空格分隔的 token 读取为字符串,然后尝试将其转换为整数。如果失败,请跳过 token ,否则将其插入 vector :

#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);
    }
  }
}

关于c++ - 读取文件时如何忽略无效输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63332805/

相关文章:

用于调用 printf 的 C++11 编译时格式字符串文字构造

c++ - 隐式转换为显式 bool 类型以对容器进行排序?

python - 在python中测试文件相关功能

C++AMP 在 16 位图像上使用纹理计算梯度

javascript - 在每个循环中删除一个 div 后如何重新排序 div id

c - 如何优化代码避免时限错误

C++ char16_t 的大小取决于什么?

c++ - const auto std::initializer_list Clang 和 GCC 的区别

c++ - 在 Linux 上断言失败后继续调试?

c++ - 不会从多插件应用程序中的每个插件加载资源