Eidbanger Eidbanger - 1 year ago 67
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.


#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;
return 0;

Text file:


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download