I am using the book "Programming : Principles and Practice Using C++(Second Edition)" by "Bjarne Stroustrup". I am stuck in the last exercise question of the chapter 4. I have tried to look up the solutions for this particular question but I am not getting the solution for the Second Edition.
There are two extensions for this question and each one requires a while-loop. Only the first while-loop is getting executed and it doesn't matter which one I place first.
The question is "Write a program where you first enter a set of name-value pairs. Terminate input with NoName 0. Each and every name entered must be unique."
Extension for the question is "Modify the program so that when you enter the name, corresponding score will be the output."
Extension for the question is "Further modify the program so that when you enter the score, corresponding names will be the output."
int main()
{
cout << "Enter a name and score side-by-side and enter 'NoName 0' when done :\n";
int scores_temp{ 0 };
string names_temp{ 0 };
vector <int> scores;
vector <string> names;
int adder{ 0 };
while (cin >> names_temp >> scores_temp)
{
if (names_temp == "NoName")
{
if (scores_temp == 0)
{
break;
}
}
else
{
for (int i = 0; i < names.size(); i++)
{
if (names_temp == names[i])
{
adder++;
}
}
if (adder == 0)
{
names.push_back(names_temp);
scores.push_back(scores_temp);
}
else
{
cout << "\nYou can't enter the same name twice.\n\n";
break;
}
}
}
for (int j = 0; j < names.size(); j++)
{
cout << names[j] << "\t" << scores[j] << "\n";
}
cout << "Enter the name to get the corresponding score and enter Ctrl+Z when done : \n";
string name_score{ 0 };
int counter{ 0 };
while (cin >> name_score)
{
for (int l = 0; l < names.size(); l++)
{
if (name_score == names[l])
{
cout << "Score of " << names[l] << " is " << scores[l] << ".\n";
}
else
{
counter++;
}
}
if (counter == names.size())
{
cout << "Name not found.\n";
}
counter = 0;
}
cout << "Enter the score to get the corresponding names and enter a character when done : \n";
int score_name{ 0 };
int incrementer{ 0 };
while (cin >> score_name)
{
for (int k = 0; k < scores.size(); k++)
{
if (score_name == scores[k])
{
cout << "Score of " << scores[k] << " was obtained by " << names[k] << ".\n";
}
else
{
incrementer++;
}
}
if (incrementer == scores.size())
{
cout << "Score not found.\n";
}
incrementer = 0;
}
keep_window_open();
return 0;
}
The header file for the program is given by Bjarne himself. The website for the header file is : http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h
There are two extensions for this question and each one requires a while-loop. Only the first while-loop is getting executed and it doesn't matter which one I place first.