Wednesday 21 September 2016

Chapter 6 // Exercise 4 - Principles & Practice Using C++

In all these exercises I am using Visual Studio Community 2015 and the header file "std_lib_facilities.h" which can be found here:


http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


My version is spelt differently so adjust the code accordingly if copying and pasting.


Chapter 6 // Exercise 4

Define a class Name_value that holds a string and a value. Rework exercise 19 in Chapter 4 to use a vector<Name_value> instead of two vectors.

#include "stdafx.h"
#include "std_lib_facilities_new_version.h"
using namespace std;

class Name_value
{
public:
string name;
int score;
};

vector<Name_value> n_s;

void getData()
{
cout << "Please enter a name, press enter, then input the score. To stop input enter 'NoName' in name and 0 in scores.\n";

Name_value data;  //variable that holds a string and int pair
char loop = 'y';

//get names and scores
while (loop == 'y')
{
cout << "Name: ";
cin >> data.name;
cout << "Score: ";
cin >> data.score;
for (int i = 0; i < n_s.size(); ++i)
{
while (n_s[i].name == data.name)
{
cout << "Sorry, that name has already been entered. Please Re-Name it: \n" << endl;
cin >> data.name;
}
}

if (data.name == "NoName" && data.score == 0)
{
loop = 'n';
}

n_s.push_back(data);  //pushes the string and int pair into the vector together
}

}

void printData()
{
cout << '\n';

//print them out
for (int x = 0; x < n_s.size() - 1; ++x)
{
cout << n_s[x].name << '\t' << n_s[x].score << '\n';
}

}

int main()
{

getData();

printData();

keep_window_open();

return 0;

}


This took some thought but didn't take me too long. The bit I tripped up on was pushing back the data into the class vector. Originally I had separate variables and was trying to push them in like this:
     n_s.name.push_back(inputname);
but obviously that wouldn't work because the compiler thought name was a function. Instead I realised I could just create a variable that held both and then push the entire variable into it's respective slots in the vector.

No comments:

Post a Comment