Boris N
Boris N

Reputation: 33

Implementing the extraction and insertion operator C++

I have a basic Student class (has to be a class)(yes there is no encapsulation and also namespace pollution pls forgive) and I would like to create custom extraction and insertion operators. After countless searches it still would not work. What I have is this

#ifndef student
#define student

#include <iostream>
#include <string>

using namespace std;

class Student
{
    public:
        string name;
        double score;

        Student();
        Student(string name, double score) : name(name), score(score) {}

        friend ostream& operator<<(ostream &out, Student &student);
        friend istream& operator>>(istream &in, Student &student);
};

#endif

#include "student.h"

ostream& operator<<(ostream &out, Student &student)
{
    out << student.name << ", " << student.score;
    return out;
}

istream& operator>>(istream &in, Student &student)
{
    if (!in >> name || !in >> score)
    {
        in.setstate(ios::failbit);
    }
    return in;
}

I have tried many things from this->name to Student::name to name to Student::student.name to changing the function signature that actually did end up working except it did not actually overload the operator. pls halp :D

Edit: As for the specific problem, it is acessing the member of the Student class within the method. student.name and student.score are throwing an

expected primary-expression before '.' token

and the bottom one is simply a relic of throwing different solution at it but it's scope error.

Edit2: The problem turn out to be a conflict with the guard in the header being called student thus the pre-processor would nuke the word student everywhere -_- Thanks for the help

Upvotes: 1

Views: 696

Answers (2)

mindriot
mindriot

Reputation: 5668

Various problems have been pointed out in the comments and in Captain Giraffe's answer. Another more critical problem is this:

You declare a variable called student in your functions; but your header actually #defines student in the header guard! So your #defined symbol clashes with your variable name, resulting in the errors you see. A recommended syntax for the header guard is something like

#define STUDENT_H_INCLUDED

Upvotes: 4

Captain Giraffe
Captain Giraffe

Reputation: 14705

I see a few problems with your >>

if (!in >> name || !in >> score)

! has higher priority than >>, use !(in >> student.name)

use student.name and student.score

Just as you did in the previous operator.

It is useful to use a const reference to the second argument for the << operator. Change the friend declaration accordingly.

Upvotes: 3

Related Questions