correct new element pusch_back to the vector

Hello I'm reading The C++ PL B. Stroustrup
and trying to overload istream >> operator
but something doing wrong and I can't catch what I'm doing wrong

Tere is code
I created struct Entry
then overloading ostream and istream operator
in void input function I'm trying to add new element
but it doesn't add new element.
what I'm doing wrong?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <string>
#include <vector>

using namespace std;

struct Entry {
	string name;
	int number;
	Entry() {};
	Entry(string s, int n): name{s},number{n}{}
};

/* << operator overloading */
ostream& operator<<(ostream& os, Entry en)
{
	return os << en.name << ": " << en.number << endl;
}

/* >> operator overloading */
istream& operator>>(istream& is, Entry en)
{
	return is >> en.name >> en.number;
}

/* push_back new Entry */
void input(vector<Entry>ph_book)
{
	Entry e; 
	cin >> e;
	ph_book.push_back(e);
}

int main()
{
	vector<Entry>phone_book = {  // vector
		{"David", 12334},
		{"Karl", 23455},
		{"Stiv", 873059},
	};
	
	//Entry e = { "Pol", 123644 };
	//phone_book.push_back(e);
	cout << "Add new number: ";

	input(phone_book); // add new element to vector phone_book 

	for (int i = 0; i != phone_book.size(); ++i)
	{
		cout << phone_book[i];
	}
	
}
Pass by reference. Note const in operator << since it should not modify the object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/* << operator overloading */
ostream& operator<<(ostream& os, const Entry& en)
{
    return os << en.name << ": " << en.number << endl;
}

/* >> operator overloading */
istream& operator>>(istream& is, Entry& en)
{
    return is >> en.name >> en.number;
}

/* push_back new Entry */
void input(vector<Entry>& ph_book)
{
    Entry e; 
    cin >> e;
    ph_book.push_back(e);
}
Thanks Chervil
but I try it dose'n help :(
Could you explain more please.

I tested the code above, it should work. Perhaps you didn't copy+paste properly?

Topic archived. No new replies allowed.