tags:

views:

102

answers:

4

I created a vector out of a struct to store multiple types of values. However, I can't get input to work.

#include "std_lib_facilities.h"

struct People{
       string name;
       int age;
};

int main()
{
    vector<People>nameage;
    cout << "Enter name then age until done. Press enter, 0, enter to continue.:\n";
    People name;
    People age;
    while(name != "0"){
                 cin >> name;
                 nameage.push_back(name);
                 cin >> age;
                 nameage.push_back(age);}
    vector<People>::iterator i = (nameage.end()-1);
    nameage.erase(i);    
}

I've also tried having the name and age variables in the main function be string/int types, and while that fixes the operator issue, it leads to an issue with function calling in the push_back line.

P.S. Is it possible to push_back multiple inputs such as...

cin >> name >> age;
nameage.push_back(name,age);

?

+8  A: 

Why not do:

People p;
cin >> p.name;
cin >> p.age;
nameage.push_back( p );

You can't just cin >> p, as istream doesn't understand how to input a "People" object. So you can either define operator>> for People, or you can just read in the individual fields into a People object.

Also, note, you need to push_back an object of type People, as that is what your vector is -- it is a People container.

FreeMemory
This way worked, but now I'm trying to output the vector. Do I need to define operator << for People?
Alex
You could, or you could output the members separately.
luke
One popular way is to define operator<<() in terms of the operator<<() of each member separately, with some sort of way to distinguish the fields.
David Thornley
+3  A: 

One option is to define an operator>> for People.

struct People
{
    friend std::istream & operator>> (std::istream & in, People & person);
};

std::istream & operator>> (std::istream & in, People & person)
{
    in >> person.name >> person.age;
    return in;
}

Then you could write:

Person p;
cout << "Enter the person's name and age, separated by a space: ";
cin >> p;
nameage.push_back (p);
Nick Meyer
+1  A: 

You probably mean:

People person;
while( cin >> person.name >> person.age && person.age != 0){
  nameage.push_back(person);
}

Or better yet you can overload the >> operator but it looks like you're looking for a more beginner solution.

A: 

I think you wanted to declare name as a string and age as an int in the main(). You are declaring them as People . This will not compile unless you have overloaded the operator >>.

Naveen