-7

以下の行から取得したこの2行のエラーを見つけるのを手伝ってもらえますか. 私は C++ の初心者なので、皆さんの助けが必要です。さらに、私はC++ではなくCプログラミング言語に慣れているため、このコードをc++に変更する方法

fgets(行、80、中)

エラー:巻き戻し(で); 行 = countLines(in);

コード:

int container:: countLines( ifstream in )
{
    int count = 0;
    char line[80];
    if ( in.good())
    {
        while ( !in.eof() )
            if (in>>line ) count++;
        rewind( in );
    }
    return count;
}

// opens the file and stores the strings
//
//    input:        string of passenger data
//                container to store strings
//
int container:: processFile( char* fn )
{
    char line[80];
    ifstream in ;
    in.open(fn);
    int count = 0;
    if ( !in.fail() )
    {
        rows = countLines(in);
        strings = new char* [rows];
        while ( !in.eof() )
        {
            if ( in>>line )
            {
                strings[count] =new char [strlen(line)+1];
                strcpy(strings[count],line);
                count++;
            }
        }
    }
    else
    {
        //printf("Unable to open file %s\n",fn);
        //cout<<"Unable to open file "<<fn<<endl;
        exit(0);
    }
    in.close();
    return count;
}
4

1 に答える 1

2

通常、ストリーム引数を渡すときは、値渡しはしません。

int container:: countLines( ifstream in )

参照渡し:

int container:: countLines( ifstream& in )

このロジックは間違っています:

    if ( in.good())
    {
        while ( !in.eof() )
            if (in>>line ) count++;
    }

このように eof() を使用しないでください。その代わり:

while (in >> line)
    count++;

これはCで巻き戻す方法です:

rewind( in );

C++ では、seekg 関数を見てください: http://en.cppreference.com/w/cpp/io/basic_istream/seekg

char* よりも std::string を使用することをお勧めします。

strings = new char* [rows];

繰り返しますが、eof() は使用しないでください。

while (in >> line)
{
    strings[count] =new char [strlen(line)+1];
    strcpy(strings[count],line);
    count++;
}
于 2013-07-13T19:24:43.977 に答える