简体   繁体   中英

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

So I have a program that reads a text file whose lines have numbers separated by commas. I get each line of the text file and parse it character by character. If I get to a comma, I just continue. When I get to something different than a comma (should be an integer), I convert that character into an integer and print it. My program isn't working as it should and sometimes it prints just 2 blank lines and sometimes it prints "1 1 2 2 3 3 4 4" and then a blank line.

Program:

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

Text file:

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

您在for循环中有错别字,应该是i = 0而不是==

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM