0

at school,I was given the class aName and asked to overload the input operator.the class has declared surname as type of char* and the surname is input from the keyboard and it must not be empty.please help me with the code.the class has declared the operator as its friend

4
Contributors
6
Replies
7
Views
7 Years
Discussion Span
Last Post by Ancient Dragon
0

post the class then we can discuss how to implement to >> operator.

class aName
{
friend std::istream operator>>(std::istream & input,aName &name);
/*input the name from the standard input stream like the keyboard and the name is never empty*/
friend std::ostream operator<<(std::ostream & output,aName name);
//it displays the name on the standard output like the screen

private:
char*surname,
       *firstname;

public:aName(char *aSurname,char*aFirstname);
void set(char *aSurname,char* afirstname)
{
if(aSurname=="")
  surname="";
else
surname=aSurname;
if(afirstname=="")
firstname="";
else
firstname=afirstname;
};
0

>>surname=aSurname;

First you have to allocate space for surname then call strcpy() to copy it

surname = new char[strlen(aSurname)+1];
strcpy(surname, aSurname);
0

The two friend functions must return a reference to the istream and ostream objects. Here's correction

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
#pragma warning( disable: 4996) // only needed for VC++ 2008 compiler

class aName
{
friend std::istream& operator>>(std::istream & input,aName &name);
/*input the name from the standard input stream like the keyboard and the name is never empty*/
friend std::ostream& operator<<(std::ostream & output,aName name);
//it displays the name on the standard output like the screen

private:
char*surname,
    *firstname;

public:
    aName() { surname = NULL; firstname = NULL;}
    aName(char *aSurname,char*aFirstname)
    {
        surname = NULL; firstname = NULL;
        set(aSurname, aFirstname);
    }

    void set(char** name, const char* aName)
    {
        if( *name != NULL)
            delete[] *name;
        *name = NULL;
        if( aName != NULL)
        {
            *name = new char[strlen(aName)+1];
            strcpy(*name, aName);
        }
    }
    void set(const char *aSurname,const char* afirstname)
    {
        set(&surname, aSurname);
        set(&firstname, afirstname);
    }
};

istream& operator>>(istream& in, aName& nm)
{
    // TODO:  complete this function.
    return in;
}

int main()
{
    aName n;
    cin >> n;
}

[edit]Oops! I just noticed I did half your homework:(

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.