0

So I'm trying to read from a text file and print each line, surrounded by two strings. For example, this is my program:

string command;

int main()
{
    while (!cin.eof()) {
        while (getline(cin, command)) {
            cout << "Can't add element : " << command << " : invalid parameter." << endl;
        }
    }  
}

The input file is in the form of 3 numbers of each line, like this:

1 1 1
2 2 2
5 4 9

So, the output should be:

Can't add element : 1 1 1 : invalid parameter.
Can't add element : 2 2 2 : invalid parameter.
Can't add element : 5 4 9 : invalid parameter.

Instead, it prints as:

 : invalid parameter.1 1 1
 : invalid parameter.1 2 2
 : invalid parameter.5 4 9

For the life of me I cannot figure out why this is happening. Any help?

jww
  • 97,681
  • 90
  • 411
  • 885
Morgan Peters
  • 33
  • 1
  • 3
  • 3
    Looks like you're reading a file with CRLF line endings on a system with LF line endings. – chris Apr 17 '15 at 16:53
  • 7
    Do not use `while(!cin.eof())`. It is _always_ wrong. Luckily your code _also_ has the right loop, so can can simply delete the incorrect `while`. – Mooing Duck Apr 17 '15 at 16:53
  • related: [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/q/5605125) – AliciaBytes Apr 17 '15 at 16:56

3 Answers3

2

Your command string has a carriage return character (\r) at the end of it. When this is output to the console, it makes the output restart at the beginning of the line. Strip the character before you print it.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Wonder why it does that though, I always thought `getline` took care of the different lineending conversions when reading a file in textmode. – AliciaBytes Apr 17 '15 at 17:09
  • @Raphael you're right, that's a good question. A quick check shows that `cin` should be text mode by default. – Mark Ransom Apr 17 '15 at 17:19
1

Note that the text " : invalid parameter." overwrites the text "Can't add element : " exactly in your output. Check your 'command' string after getline(), I'm sure you'll have 'CR' (ascii 13) as the last character, so after your 'command' string is written out, further output continues at the line beginning.

If I was to speculate why this is happening, I'd guess your terminal emulator sends out 'CRLF' where your system expects only 'LF' as the end of line character.

Marek Fekete
  • 641
  • 3
  • 16
-1

Try something like below (it might help you)

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open()) {
    while ( getline (myfile,line) ) {

      cout << "Can't add element : " << line<< " : invalid parameter." << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}