解析文件时输出错误

Wrong output when parsing the file?

本文关键字:输出 错误 文件      更新时间:2023-10-16

我使用下面的代码来解析一个文件。

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