tags:

views:

107

answers:

4

I'm reading data.txt:

//////////////////////////////////////////////////

data.txt:

//////////////////////////////////////////////////

MissionImpossible3
3
TomCruise
MaggieQ
JeffChase

Here's code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
 ifstream fin("data.txt");
 string FilmName, ActorName;
 getline(fin,FilmName,'\n');
 cout << FilmName << endl;
//    cout << fin.tellg() << endl; //if I add this line to
// get current reading position of data.txt, the program just
// can't work as if tellg() triggered some error. So I removed
// all tellg(). What's the reason for this and what shall I do
// if I want to get current reading position?
 int a;
 fin >> a;
 cout << a << endl;
// cout << fin.tellg() << endl;
 getline(fin,ActorName,'\n');
// cout << fin.tellg() << endl;
    for(int i=0;i<a;i++)
    {
     getline(fin,ActorName,'\n');
     cout << ActorName << endl;
//     cout << fin.tellg() << endl;
    }

 getchar();
}

Unexpected output is:


MissionImpossible3
24
0
-1
-1

I'm using Dev-c++ and Windows XP. I'll appreciate it if you guys give it a try and paste your results and environment. Maybe there is some problem with my system or compiler.

Another version of input/output:

data.txt:

MissionImpossible3
3
TomCruise
MaggieQ
JeffChase

WarOfTheWorlds
2
TomCruise
DakotaFanning

SharkTale
3
JackBlack
RobertDeNiro
WillSmith

HideAndSeek
2
DakotaFanning
RobertDeNiro

TheAdventureOfPlutoNash
2
WillSmith
EddieMurphy

ShowTime
2
RobertDeNiro
EddieMurphy

output:

MissionImpossible3
49
0
-1
-1
A: 

I compiled and ran your code with the tellg lines re-enabled, and it seemed to work fine. The output I got was:

MissionImpossible3
20
3
21
23
TomCruise
34
MaggieQ
43
JeffChase
52

What exact result do you get when you try to run it? [Yes, this is really more of a comment than an answer, but it won't fit in a comment.]

Jerry Coffin
I got:<br>MissionImpossible3<br>24<br>0<br>-1<br>-1<br>
L.Lawliet
@L.Lawliet: Unfortunately, you can't enter a newline in a comment. As for the values, it looks like it ran into an error in reading; you might want to see if `errno` (for one possibility) tells you anything.
Jerry Coffin
@L.Lawliet: that pretty much leaves Potatoswatter's explanation as a best first guess. I'd do a hex dump of the text file and see what it really has marking the ends of the lines -- some Windows code deals with Unix and/or MacOS text files, but some doesn't, and what you're seeing probably results from a difference between Notepad's and your standard library's handling of line ends.
Jerry Coffin
add ios::binary when opening the txt and it works! Why?
L.Lawliet
Because your input isn't properly encoded as a text file for the platform you're using. The fact that it "works" when opened as binary is mostly accidental.
Jerry Coffin
+2  A: 

It says it consumed 24 characters after the first line, then failed to get a number. However, MissionImpossible3 only has 18 characters.

I suspect you have a line encoding incompatiblity. Your file is saved with \n endings, while Windows iostreams expects \r\n. The 3 in the input gets thrown away as the system expects a \n. Then the next input is non-numeric and it enters an error state.

Try copy-pasting the input data to a new file in Notepad.

Potatoswatter
But I didn't see this encoding problem happen before and I view the txt file pretty well using notepad. I tyied creating a new file and copy-pasting. Problem still exists.
L.Lawliet
add ios::binary when opening the txt and it works! Why?
L.Lawliet
@L.Lawliet: `ios::binary` prevents line encoding translation. Did you try looking at it in a hex editor, or copy-pasting from, say, this webpage to eliminate the possibility of a conflict?
Potatoswatter
Yes, I tried. Just see the first comment. I pasted it from this page. What does it mean by "preventing line encoding translation"?
L.Lawliet
@L.Lawliet: Unix and Windows use different character sequences to represent the end of a line. C `stdio` and C++ `iostream` make all files, no matter what platform you're running on, look like Unix. This is a good thing because Windows uses two characters, `\r\n`, to represent the end of a line. Does this sound familiar to you?
Potatoswatter
But I checked my file in HEX, the file is save with \r\n endings, or 0xOD 0x0A at the end of each line.
L.Lawliet
… anyway, if you mix and match line endings in a given file, or sometimes even if a file is consistent but just foreign, the mini-parser might screw up. The details are implementation-defined, aside from the C and C++ standards prescribing that a line ending is represented by a single newline character, and not the carriage return character.
Potatoswatter
@L.Lawliet (just got last message): If the file is entirely consistent, I don't know how else to help. That's the only thing I know of that `binary` does, and I already suspected it before that.
Potatoswatter
And it's tricky that when I add other films and actors into this text file, the first wrong tellg() will return 49 instead of 23.
L.Lawliet
@L.Lawliet: What happens if you use the console, `cin`?
Potatoswatter
Use cin? How? Replace all fin with cin?
L.Lawliet
@L.Lawliet: yes
Potatoswatter
@Potatoswatter: After the first line of input (film name), I got the output of film name and -1. And what is the effect of cin.tellg()? I've never used it like this before.
L.Lawliet
@L.Lawliet: Since the tellg call is only a diagnostic, you can comment it out. The point is to see whether the program behaves better with interactive input, which is all but guaranteed to have native line endings.
Potatoswatter
@Potatoswatter: I mentioned in my question about that. If I just remove all tellg, my program behaves normal.
L.Lawliet
@L.Lawliet: Ahh, forgot. Strange coincidence, but I'm working on fixing a similar problem with GCC's `tellg` implementation… the function *can* be implemented such that it would have problems if called at a Windows newline. Try putting `fin.unget()` before the `fin.tellg()`, to "put the stream in reverse" and eject the newline back into the sequence. Then, the following `>>` operation will treat it as whitespace. An ugly workaround for an ugly bug.
Potatoswatter
@Potatoswatter: I got an endless loop of -1...
L.Lawliet
@Potatoswatter: So I don't think it's a problem of windows or something like \r\n Just a problem with tellg.
L.Lawliet
@L.Lawliet: Well, for the loop part, the `getline` operations are not separated by `>>` operations, `unget` will need to be followed by skipping the newline. The simplest solution is `ignore`, perhaps that will work correctly.
Potatoswatter
Still endless loop... Maybe you can try my program on windowsXP and dev-c++ yourself. I'm kind of mad now...
L.Lawliet
And as I added in question, if the file is longer, tellg gives different values though I still only read in the first few lines. You may think about this too.
L.Lawliet
@L.Lawliet: I don't have a Windows installation on hand, and I don't even know what dev-c++ is. Why not upgrade to the free edition of Visual Studio? Whatever kind of bug this is, any decent implementation should work properly
Potatoswatter
OK I find if I use VC 6.0 there is no problem. So VC is still a best envirenment under Windows although I've never met any problem with dev-c before. I have uninstalled dev-c...
L.Lawliet
+1  A: 

Try opening the file in binary mode:

ifstream fin("data.txt", ios::binary);
Goutham
yeah it works! But as I thought, read or write a file in binary or not is determined by the function you use(fread or >> , fwrite or << ), what does this ios::binary do in detail?
L.Lawliet
@L.Lawliet: `ios::binary` prevents line ending encoding translation. So while it might work with this file, it will tend to generate Unix style files, misinterpret Windows files, and corrupt Windows files you already have. Don't use binary for text.
Potatoswatter
Then what shall I do, I also don't think it's a good idea to make a text file work like a binary file.
L.Lawliet
Goutham
@Goutham: that's probably because reading one byte from a Windows text file can consume two bytes of file offset. As long as you don't expect the number of bytes returned to match the file position, it should be fine.
Potatoswatter
A: 

Creating the ifstream with std::ios::binary fixed the tellg so it returned the correct position in the file in my code as well (Win 7 64-bit). As L.Lawliets asks - Why??!

Pete