解析文件时输出错误
Wrong output when parsing the file?
我使用下面的代码来解析一个文件。
std::string line;
std::ifstream infile("C:\t50_20_1.td");
int num;
int pred;
int succ;
while (std::getline(infile, line))
{
std::istringstream iss(line);
while(iss >> num || !iss.eof()) {
if(iss.fail()) {
iss.clear();
continue;
} else {
std::cout<<num<<std::endl;
}
}
std::cin.ignore();
}
我正在尝试打印以下文件
中的所有数字50
1 35 11 3 13 10 5 11 2 19 1 21 10 23 2 26 3 29 6 35 5 42 10 44 5
2 3 12 8 7 15 12 19 9 24 6 27 13 29 7 32 8 34 6 35 8 37 9 38 12 39 9
3 19 7 4 15 8 2 10 7 15 12 21 11 26 9 36 10
4 35 8 5 13 7 7 10 8 13 13 20 1 21 5 44 1 48 15
但是当程序结束时,我只得到一个数字作为输出
50
我建议您删除!iss.eof()条件,因为它在while循环中是不必要的。必须按Enter键才能继续解析下面的行。请看下面的代码。此外,我建议您添加"using namespace std",这意味着在必要的地方使用std::,可以使代码更具可读性。最后,您声明的一些变量实际上并没有使用,因此它们已从下面的代码中删除。
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;
int main (int argc, char ** argv)
{
string line = "";
ifstream infile("C:\t50_20_1.td");
int num = 0;
while (getline(infile, line))
{
istringstream iss(line);
while(iss >> num) {
if(iss.fail()) {
iss.clear();
continue;
} else {
cout << num << endl;
}
}
std::cin.ignore();
}
return 0;
}
示例输出(仅选择输出,所有数字都用上述代码输出)
50
...
44
5
...
39
9
...
48
15
相关文章:
- 输出错误,问题是找到总和5000位数字cpp
- 使用复制构造函数的程序输出错误
- 异或字符串加密/解密输出错误
- 在linux上使用g++输出错误,在windows上更正
- 使用递归函数 (c++) 将长字符串转换为整数时输出错误
- ECDSA 密钥对生成输出错误
- fscanf() 输出错误的值
- 输入 1024 后十进制到二进制转换的输出错误?
- 输出错误命令的条件语句
- cuSparse (cusparseDcsrgemm) 中的矩阵乘法输出错误的结果
- 为什么 du -sh 输出错误大小的内存映射文件
- VS2017 的输出错误,但 mingw 有效
- 如何使FFMPEG C 代码不输出错误消息
- 乘以时输出错误.这是我编译器中的错误吗?C
- 输出错误:两个不同编译器上的不同输出:Prime Cryptarithm USACO
- 为什么输出错误崩溃
- C++输入/输出错误
- 尝试用 c++ 制作一个简单的加法器.编译成功,但输出错误
- 当我使用此合并排序代码运行时,输出错误
- 递归功能输出错误的值