using a simple class

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

[code language=”cpp”]
// Philipp Siedler
// Bjarne Stroustrup’s PP
// Chapter 6 Exercise 4

#include "std_lib_facilities.h"

class nameValue {
public:
nameValue(string n, int a) : name(n), age(a) { }
string name;
int age;
};

int main()
try
{
vector<nameValue> nameAndAge;

string nameTemp;
int ageTemp;

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 < nameAndAge.size(); i++) {
if (nameAndAge[i].name == nameTemp) {
error("This name already exists ", nameTemp);
}
}
nameAndAge.push_back(nameValue(nameTemp, ageTemp));
}
}
else {
error("Bad input");
}
}

for (int i = 0; i < nameAndAge.size(); i++) {
cout << "Name: " << nameAndAge[i].name << " Score: " << nameAndAge[i].age << "\n";
}

keep_window_open(".");
}

catch (runtime_error e) {
cout << e.what() << "\n";
keep_window_open(".");
}
catch (…) {
cout << "Exiting \n";
keep_window_open(".");
}

/*class Name_value { // much like Token from 6.3.3
public:
Name_value(string n, int s): name(n), score(s) { }
string name;
int score;
};

int main()
try
{
vector<Name_value> pairs;

string n;
int v;

while (cin>>n>>v && n!="NoName") { // read string int pair
for (int i=0; i<pairs.size(); ++i)
if (n==pairs[i].name) error("duplicate: ",n); // chek for duplicate
pairs.push_back(Name_value(n,v));
}

for (int i=0; i<pairs.size(); ++i)
cout << ‘(‘ << pairs[i].name << ‘,’ << pairs[i].score << ")\n";

keep_window_open("~"); // For some Windows(tm) setups
}*/
[/code]

Leave a Reply