Eidbanger Eidbanger - 4 months ago 8
C++ Question

Different outputs from program ran multiple times on a 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

Answer

You have a typo in the for loop, should be i = 0 and not with ==