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,
MissionImpossible3only has 18 characters.I suspect you have a line encoding incompatiblity. Your file is saved with
\nendings, while Windows iostreams expects\r\n. The3in 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.