首頁 > 程式設計 > Read file , and count the IDs.

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.

分類:程式設計 標籤:
  1. 仍無迴響。
  1. No trackbacks yet.

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s

%d 位部落客按了讚: