Jose Mikal
Jose Mikal

Reputation: 11

fstream syntax in a class

This is my student class. The function static int readRecord(fstream &, Student s[]);:

#ifndef STUDENT_H
#define STUDENT_H
#include <fstream>
class Student
{
public:
Student();
Student(char* n, int g[]);
char* getName();
void setName(char* n);
void setGrade(int g[]);
double getGradesAverage(); 
static int readRecord(fstream &, Student s[]); 
static void display(Student s[], int  students);
static void sort(Student s[], int students);

private:

char name[30];
int grades[5];

};


#endif

in my cpp I have this:

int Student::readRecord(fstream & in, Student s[])

{

int j = 0;

if (!in)

{
    cout << "cannot open the file or file does not exists\n";
    exit(0);
}

else

{
    char name[30];
    int g[5];
    char ch;
    while (in)

    {
        in >> name;
        for (int i = 0; i<5; i++)
        {
            in >> g[i];
            if (i != 4)
                in >> ch; 
        }

        s[j].setName(name);
        s[j].setGrade(g);
        j++;

    }
}

return j - 1;

}

I get this compiler errors:

error C2061: syntax error : identifier 'fstream'

and

error C2511: 'int Student::readRecord(std::fstream &,Student [])' : overloaded member function not found in 'Student'

Upvotes: 1

Views: 241

Answers (1)

deW1
deW1

Reputation: 5660

#ifndef STUDENT_H
#define STUDENT_H
#include <fstream>

class Student
{
public:

  Student();
  Student(char* n, int g[]);
  char* getName();
  void setName(char* n);
  void setGrade(int g[]);
  double getGradesAverage(); 
  static int readRecord(std::fstream &file, Student s[]); 
  static void display(Student s[], int  students);
  static void sort(Student s[], int students);

private:

  char name[30];
  int grades[5];

};

You have to use std::fstream if you don't work with using namespace std.

A better alternative would be to do using std::fstream instead of using namespace std though.

Another problem I see is that you forgot to declare a name for the fstream object.

static int readRecord(std::fstream &file, Student s[]); 
//                    ^^^          ^^^^^

Also since you are using C++ you should not use char arrays anymore for strings but instead std::string.

I would generally replace all the array stuff with std::vector.

Upvotes: 2

Related Questions