为什么在同一个文本文件上多次运行的程序会有不同的输出

Why is there different outputs from a program ran multiple times on the same text file?

本文关键字:程序 输出 运行 同一个 文本 文件 为什么      更新时间:2023-10-16

所以我有一个程序可以读取一个文本文件,该文件的行中有用逗号分隔的数字。我获取文本文件的每一行,并逐个字符地对其进行解析。如果我说到逗号,我就继续。当我得到不同于逗号(应该是整数)的东西时,我会将该字符转换为整数并打印它。我的程序无法正常工作,有时只打印两行空行,有时会打印"1 1 2 2 3 4",然后再打印一行空行。

程序:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
    ifstream infile(argv[1]);
    string str;
    int num, i;
    while (!infile.eof()) {
        getline(infile, str);
        if (str.length() == 0) continue;
        else {
            for (i == 0; i < str.length(); ++i) {
                if (str[i] == ',') continue;
                else {
                    num = str[i] - '0';
                    cout << num << " ";
                }
            }
        }
        cout << endl;        
    }
    infile.close();
    return 0;
}

文本文件:

1,1,1,2,2,3,3,4,4
2,3,4,5,5

您在for循环中有一个拼写错误,应该是i = 0,而不是==