-7

Could you help me find what is error with this 2 line which I took from the below line. Since I am a newbie in c++, I need your help folks. In addition, how to change this code to c++ because I am used to C programming language rather than C++

fgets( line, 80, in )

error : rewind( in ); rows = countLines(in);

Code:

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;
}
Pramono Wang
  • 1
  • 1
  • 2
  • Clearly you are using C++ for you are using the namespace operator – turnt Jul 13 '13 at 19:15
  • Look here (http://en.cppreference.com/w/cpp/io/c/rewind). Rewind is a C-function which operates on FILE but you try to rewind a C++ stream. – Vincent Jul 13 '13 at 19:22
  • 2
    [`while (!eof())` is wrong.](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – chris Jul 13 '13 at 19:52

1 Answers1

2

Generally, when you pass a stream argument you don't pass by value:

int container:: countLines( ifstream in )

You pass by reference:

int container:: countLines( ifstream& in )

This logic is wrong:

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

Don't use eof() this way. Instead:

while (in >> line)
    count++;

This is how to rewind in C:

rewind( in );

In C++, look at the seekg function: http://en.cppreference.com/w/cpp/io/basic_istream/seekg

Prefer to use std::string over char*:

strings = new char* [rows];

Again, don't use eof():

while (in >> line)
{
    strings[count] =new char [strlen(line)+1];
    strcpy(strings[count],line);
    count++;
}
Bill
  • 14,257
  • 4
  • 43
  • 55