Anytime I try to compile the code below I get the following error message.
E:\Users\Cosman\Desktop\C++ PRACTICE\read2.cpp|52|error: no match for 'operator<<' in 'std::cout << m'
How do I correct this?

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

class A
{
    private:
    char name[50];
    char gender[8];
    int age;

    public:
    A(char *n, char *g, int a);
    friend ofstream &operator<<(ofstream &target, A obj);
    friend ifstream &operator>>(ifstream &target, A obj);
};

A::A(char *n, char *g, int a)
{
    strcpy(name, n);
    strcpy(gender, g);
    age = a;
}

ofstream &operator<<(ofstream &target, A obj)
{
    target<<obj.name<<endl;
    target<<obj.gender<<endl;
    target<<obj.age<<endl;
    return target;
}

ifstream &operator>>(ifstream &target, A obj)
{
    target.getline(obj.name, 50).getline(obj.gender, 6)>>obj.age;
    return target;
}

int main()
{
    char n[50];
    char s[8];
    int a;
    cout<<"Enter name: ";
    cin.getline(n, 50);
    cout<<"Enter gender: ";
    cin.getline(s, 8);
    cout<<"Enter age: ";
    cin>>a;
    A m(n, s, a);
    cout<<m;
    return 0;
}

Recommended Answers

The problem is you defined you function as using ofstream and ifstream. These are the objects used for handling files. If you want to use you class with cin and cout you need to use istream and ostream.

Jump to Post

All 2 Replies

The problem is you defined you function as using ofstream and ifstream. These are the objects used for handling files. If you want to use you class with cin and cout you need to use istream and ostream.

Thanks NathanOliver. My program now compiles.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.