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