Read file , and count the IDs.

I’ve forgot the useage of fstream.getline function.

#include <iostream>
#include <fstream>
#include <stdio.h>
using namespace std;

int main(int argc,char * argv[])
{
fstream MyFileStream;
char ReadInput[1024];
int IdMax= -1 , Counts = 0;
MyFileStream.open("Book_data.prn",ios_base::in);
while(!MyFileStream.eof() && MyFileStream.getline(ReadInput,1024))
{
int ReadId=atoi((strtok(ReadInput," ")));
if(IdMax < ReadId)
{
cout << "ID:" << ReadId << endl;
++Counts;
IdMax = ReadId;
}
}
cout << "Total Counts is " << Counts << endl;
MyFileStream.close();
return 0;
}

If you just write the code as the following:

   while(!MyFileStream.eof())
{
MyFileStream.getline(ReadInput,1024);
int ReadId=atoi((strtok(ReadInput," ")));
if(IdMax < ReadId)
{
cout << "ID:" << ReadId << endl;
++Counts;
IdMax = ReadId;
}
}

The segment fault is happened! Because the function fstream.getline may read the end of line in the file, this result in empty string in ReadInput. Hence, the segment fault is happened.

[modified on Jan 4,2011]
Why!Because the action of eof() or feof() in C/C++ is that returns true when the last read action get “end of file” error!, the getline() function gets a segment fault. If you want to know the detail of eof() and feof() functions, go to here, please.

This entry was posted in 程式設計. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *