So I have been studying programming from the book PPP by Bjarne Stroustrup and there is the following assignment:
- Write a program where you first enter a set of name·and·value pairs, such as Joe 17 and Barbara 22. For each pair, add the name to a vector called names and the number to a vector called scores (in corresponding positions, so that if names[7]=="Joe" then scores[7]==18). Terminate input by the line No more ("more" will make the attempt to read another integer fail ). Check that each name is unique and terminate with an error message if a name is entered twice. Write out all the (name,score) pairs, one per line.
- Modify the program from exercise 19 so that when you enter a name, the program will output the corresponding score or "name not found".
Modify the program from exercise 19 so that when you enter an integer, the program will Output all the names with that score or "score not found". So this is the code I wrote:
using namespace std; int main() { vector <string> names; string name; vector <int> scores; int score; string finish = "no more"; cout << "Please write a player's name and the player's score: \n"; while (name != "|") { cin >> name; cin >> score; names.push_back(name); scores.push_back(score); cin.ignore(); } for (size_t j = 0; j < scores.size(); j++) { for (size_t p = 0; p < scores.size(); p++) { if (names[j] == names[p] && j != p) { cout << "Error! You have reiterated the name: " << names[j] << "\n"; system("pause"); return 1; } } } cout << "Please insert a name to see it's score:\n"; string s = " "; cin >> s; for (size_t d = 0; d < scores.size(); d++) { if (s == names[d]) { cout << names[d] << "'s score is: " << scores[d] << "\n"; } } system("pause"); }
Now my problem is quite simple I believe. In the second cin (cin >> s) the compiler simply seems to skip this line and terminates the program instead of letting me write an input. I read online that it is because that you can't use cin twice so when I added the line cin.ignore()
, hoping that the problem will be solved, it did not help solve the problem. Any tips on how to fix this?