彙整

Archive for 2010 年 12 月

Read file , and count the IDs.

十二月 22, 2010 發表迴響

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.

類別:程式設計 標籤:

冒痘痘的位置可能顯示出身體的警訊

十二月 12, 2010 2 留言

臉上是否常常長痘痘?這代表妳/你 的身體代謝可能出了些問題…

繼續閱讀…

類別:生活
Follow

Get every new post delivered to your Inbox.