name and age pairs [name called by age]

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 4 Exercise 21
Using std_lib_facilities.h by Bjarne Stroustrup.

//	Philipp Siedler
//	Bjarne Stroustrup's PP
//	Chapter 4 Exercise 21

#include "std_lib_facilities.h"

int main()
try
{
	vector<string> names;
	string nameTemp;

	vector<int> ages;
	int ageTemp;
	int ageInput;
	int ageCheck = 0;

	bool check = true;

	while (check == true) {
		cout << "Enter name and age pairs to be collected, or 'noname' and '0' to end the entry.\n";

		if (cin >> nameTemp >> ageTemp) {
			if (nameTemp == "noname" && ageTemp == 0) {
				check = false;
			}
			else {
				for (int i = 0; i < names.size(); i++) {
					if (names[i] == nameTemp) {
						error("This name already exists ", nameTemp);
					}
				}
				names.push_back(nameTemp);
				ages.push_back(ageTemp);
			}
		}
		else {
			error("Bad input");
		}
	}

	cout << "Enter a integer to look for\n";
	cin >> ageInput;

	for (int i = 0; i < ages.size(); i++) {
		if (ages[i] == ageInput) {
			cout << "You entered: " << ageInput << " . Corresponded name is " << names[i] << "\n";
			ageCheck++;
		}
	}

	if (ageCheck == 0) {
		cout << ageInput << " . Could not be found in the list of ages.\n";
	}

	keep_window_open(".");
}

catch (runtime_error e) {
	cout << e.what() << "\n";
	keep_window_open(".");
}
catch (...) {
	cout << "Exiting \n";
	keep_window_open(".");
}
Output:
Enter name and age pairs to be collected, or 'noname' and '0' to end the entry.
Peter 20
Enter name and age pairs to be collected, or 'noname' and '0' to end the entry.
Hans 20
Enter name and age pairs to be collected, or 'noname' and '0' to end the entry.
noname 0
Enter a integer to look for
20
You entered: 20 . Corresponded name is Peter
You entered: 20 . Corresponded name is Hans
Please enter . to exit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.