需要c ++代码的帮助

时间:2013-07-13 19:13:04

标签: c++

你能帮我找一下这条2行的错误吗?由于我是c ++的新手,我需要你的帮助。另外,如何将此代码更改为c ++,因为我习惯使用C编程语言而不是C ++

fgets(第80行,第80行)

错误: 倒带(in); rows = 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;
}

1 个答案:

答案 0 :(得分: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

首选使用std :: string over char *:

strings = new char* [rows];

同样,不要使用eof():

while (in >> line)
{
    strings[count] =new char [strlen(line)+1];
    strcpy(strings[count],line);
    count++;
}
相关问题