1

ANSWER

Even though everything was compiled and run on windows, I completely forgot tellg behaves as an unformatted input function and cannot be used reliably in text mode which is why I see the discrepancy. See std::basic_istream::tellg for details.

ORIGINAL

The following extremely simple program is giving me different results with gcc 4.7.1 (mingw) and MSVC2012:

#include <iostream>
#include <fstream>
int main()
{
    std::ifstream in("test.txt");
    int i;
    in >> i;
    std::cout << in.tellg() << std::endl;
}  

The test.txt is as follows (IMPORTANT NOTE: There is a newline after the 1)

1

MSVC Output:

1

gcc 4.7.1 (mingw) Output:

2

Question

I believe gcc is correct since operator>> should extract the newline, but am not certain. Which compiler is correct?

(Note: Both programs were compiled and run on windows).

HEX of text file

31 OD OA

If I create a linux-like line ended file, i.e. 31 0A, MSVC outputs 0 and gcc outputs 1.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166

1 Answers1

2

Following my comment, Please refer to this excellent post Why does my program produce different results on Windows and Linux, about file reading with ifstream?

Community
  • 1
  • 1
Shmil The Cat
  • 4,548
  • 2
  • 28
  • 37
  • I'm using mingw. I didn't run anything on linux. Everything was compiled and run on the same platform (windows). – Jesse Good Mar 30 '13 at 22:07
  • @JesseGood But your gcc uses stdlibc++, while MSVC uses their implementation, so I think the last paragraph of R.MartinhoFernandez's answer in that link still applies. – us2012 Mar 30 '13 at 22:17
  • I just realized you are right. I expected mingw to interpret `\r\n` as `\n`, but it doesn't. Stupid mistake by me. – Jesse Good Mar 30 '13 at 22:29
  • I remembered the answer now (see my edit), it's not that mingw does not follow windows conventions, it's that `tellg` behaves as an unformatted input function. `mingw` properly interprets `\r\n` as newlines. Thanks for the help in finding the answer. – Jesse Good Mar 30 '13 at 22:45