Maximka
Maximka

Reputation: 119

Cpp getline in a while loop works once, then reads until the end of the file

I am writing a program that take a command redirected file as the standard input, so instead of cin getting input from the keyboard, I run my program with ./teamBalancer < inputFile.txt > outputFile.txt.

The problem I'm having is that getline in the while loop reads the first line perfectly and outputs fine, but then it just reads the rest of the file in one line. I have tried everything from stringstreams to just getline and have read so many forums. Why is this happening?

Here is my code:

  //USER INPUT--------------------------------------------------------------
  while (cin) {
   string attackString, defenseString;
   getline(cin, attackString, ',');
   getline(cin, defenseString);

   int attack, defense;
   attack = atoi(attackString.c_str());
   defense = atoi(defenseString.c_str());
   cout<<attack<<" "<<defense<<endl;
  }

and the sample input is this:

5,1

9,1

7,4

1,3

1,3

10,4

4,5

7,4

and the corresponding output is...

5 1

9 1

0 0

Both of these are in txt files and the 0 0 for the last output is because the last line is empty? I don't understand why getline can't continue reading the file line by line like it does with the first one.

Thank you so much to anyone who helps and if you need any clarification please let me know! Thank you :)

Upvotes: 0

Views: 812

Answers (1)

zinnjonas
zinnjonas

Reputation: 66

the Code you presented looks good. I tested it under Windows without any changes and got the following result:

5 1
9 1
7 4
1 3
1 3
10 4
4 5
7 4
0 0

So it looks like your input file encoding is messed up. Can you please check the line endings of your input txt. Are they all the same and are the EOL chars the default one for your system?

The 0 0 in the last row is that cin still contains something at the end (the EOF char) but it is not able to translate it to the wished numbers, to avoid this you can use this:

 while (!cin.eof())

Now you are checking if you are on the end of a file.

Sorry currently i can not write comments.

br,
zinnjonas

Upvotes: 1

Related Questions