Vectors problem.

Hi,
I am going through the new stroustrup book , Programming: Principles and Practice using c++. I use Visual C++ 2008 express.
It is a program where you enter name and value pairs and check whether each name is unique.
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
#include "std_lib_facilities.h" // library by Stroustrup for this book

int main() {
	vector<string> names;
	string n;
	vector<int> scores;
	int s, i;
	cout << "Enter the name and score of each person(Terminate entry with \"stop\").\n";
	while (n != "stop") {    // to terminate the code
		getline(cin, n);
		names.push_back(n);
		cin >> s;
		scores.push_back(s);} 
	sort(names.begin(), names.end()); 
	sort(scores.begin(), scores.end());
	for(i = 0; i < names.size(), i < scores.size();i++){ // Printing the table
		if(names[i] == names[i+1]){
			cout << "Error: " << names[i] << " entered twice. Deleting ...\n";
			names.erase(names.begin() + i);
			scores.erase(scores.begin() + i);
		}
		cout << '\n' << names[i] << "\t"<< scores[i];
	}
	keep_window_open();
	return 0;
}

After entering two names and scores , the program doesn't input whatever I type.
I suspect there is something wrong with the first while loop. I've tried altering but sometimes it shows "Vector subscript out of range".
Please help! C++ is my first programming language.
Also can you suggest ways of terminating such loops ?

The comma operator just returns the value of the first expression so i < names.size(), i < scores.size() is the same as just i < names.size(). Use && to check two conditions. i < names.size() && i < scores.size()
Not terribly important given the context but the comma operator discards the value of the first expression, so i < names.size(), i < scores.size() is equivalent to i < scores.size()
The problem is that after cin >> s; the new line character stays in the input buffer. So next time then getline(cin, n); is executed an empty string is read. But you do not know that and enter a name that becomes an input for cin >> s; . An input error occurs and you can not enter something any more.
I suggest to substitute getline(cin, n); for cin>> n;

Also your program contains many other errors.
The problem is that after cin >> s; the new line character stays in the input buffer. So next time then getline(cin, n); is executed an empty string is read. But you do not know that and enter a name that becomes an input for cin >> s; . An input error occurs and you can not enter something any more.
I suggest to substitute getline(cin, n); for cin>> n;


I tried using cin >> n; too but the result is same
Topic archived. No new replies allowed.