0

I'm trying to run this code:

string p = "Test.txt";

ifstream fid(p.c_str());

while(!fid.eof()) {
    getline(fid,p);
    cout << "|s|" << p << "|e|" << endl;
}

But the result put's somehow of since it is like this:

 |e|line1
 |e|line2
 ...

instead of:

 |s|line1|e|
 |s|line1|e|
 ...

Could somebody please explain to me what I'm doing wrong?

yours magu_

magu_
  • 4,766
  • 3
  • 45
  • 79
  • That is incorrect - I receive a compile error without the c_str() on MinGW. – IanPudney Jun 10 '13 at 14:27
  • @soon It is required in the absence of C++11 support. – juanchopanza Jun 10 '13 at 14:27
  • 1
    I receive your expected output when I run your code. What compiler and OS are you using? – IanPudney Jun 10 '13 at 14:28
  • Woops, sorry, missed that. – awesoon Jun 10 '13 at 14:28
  • I'm using XP 32Bit - Using the cygwin gcc compiler, should be the up to date version. – magu_ Jun 10 '13 at 14:33
  • 2
    I suspect your lines end with the carriage-return character `'\r'`. You can try something like `if (!p.empty() && p.back()=='\r') p.pop_back();` (C++11 only; else: `if (!p.empty() && p[p.length()-1]=='\r') p.erase(p.length()-1);`) before your output. – gx_ Jun 10 '13 at 14:34
  • @magu_: "last version" is very subjective :) When asked about a compiler version, it's best to give the output of `g++ --version`. – slaphappy Jun 10 '13 at 14:40
  • 2
    Aside: not `while(!fid.eof())` [again](http://stackoverflow.com/questions/5837639/eof-bad-practice/5837668#5837668) [please](http://stackoverflow.com/questions/1494342/end-of-file-in-c/1494383#1494383). – n. m. could be an AI Jun 10 '13 at 14:49
  • 3
    Cygwin gcc (or the standard library to be precise) does not handle Windows line endings correctly (it's a part of a Unix-like environment after all). Try mingw gcc or any other compiler built for Windows. – n. m. could be an AI Jun 10 '13 at 15:05

1 Answers1

0

Thx gx_ for the answer.

I should have known it actually since I switch between Win/Linux...

 p.erase(remove(p.begin(), p.end(), '\r'), p.end());

Did solce the problem. Thx for the help. I still wonder though what my program was doing though. But I guess this is one of this unstable cases you should not build your program on^^

thx again magu_

magu_
  • 4,766
  • 3
  • 45
  • 79
  • It was the terminal interpretation of `'\r'` (carriage-return), which moves the cursor to the beginning of the current line. The next three characters `|e|` then overwrote the `|s|` which previously occupied that location. – Ben Voigt Jun 11 '13 at 06:27
  • @BenVoigt I wouldn't have said it better (and that concise), thank you =) magu_ you're welcome – gx_ Jun 11 '13 at 06:31