0

"Write a class named Person that represents the name and address of a person. Use a string to hold each of these elements. Add operations to read and print Person objects to the code you wrote."

Note I haven't reached the section on access control yet.

#include <iostream> 
#include <string>

using std::string;

struct Person
    {
        string name_var, address_var;
    };

std::ostream &print(std::ostream&, const Person &);
std::istream &read(std::istream&, Person &);


std::istream &read(std::istream &is, Person &item)
    {
         is >> item.name_var >> item.address_var;
         return is;
    }

std::ostream &print(std::ostream &os, Person &item)
    {
         os << item.name_var << " " << item.address_var;
         return os;
    }  

With this I can only read single worded names and addresses if I use std::cin as the first argument to read, which isn't very useful. Can you somehow use getline?

user110503
  • 115
  • 4

2 Answers2

3

You can use:

std::getline(is, item.name_var);

You can also specify a delimiter char as the third argument

KABoissonneault
  • 2,359
  • 18
  • 17
  • Should I separate reading in names and addresses into two functions? I mean in the code I gave the user inputs two strings for a name and address, but your example would only read in a name. – user110503 Jun 15 '15 at 12:20
  • @user110503 Nothing stops you from writing code after my std::getline example. Instead of changing it to another function, why not define read and print as operator>> and operator< – KABoissonneault Jun 15 '15 at 12:29
  • I haven't done operator overloading yet, if that is what it is under. – user110503 Jun 15 '15 at 14:45
0

Look at one thing: you have used a space to separate name and address. Now, in order to know when the name is over, you need to use some other delimiter for name. Another delimiter means you need to enclose the name in e.g. double quote (") and then, while reading the name, get input until you get the second delimiter.

marom
  • 5,064
  • 10
  • 14