主頁 > 程式設計 > 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

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s

%d 位部落客按了讚: