0

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
Anton Savelyev
  • 732
  • 7
  • 21
  • 3
    See [**Why is iostream::eof inside a loop condition considered wrong?**](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – Khalil Khalaf Aug 02 '16 at 19:32
  • 1
    `for (i == 0; i < str.length(); ++i) {` you mean `for (i = 0; i < str.length(); ++i) {` right? – DimChtz Aug 02 '16 at 19:34

1 Answers1

2

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

norok2
  • 18,523
  • 3
  • 47
  • 78