开发者

Problem with istream::tellg()?

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


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.


Try opening the file in binary mode:

ifstream fin("data.txt", ios::binary);


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??!


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.]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜