Originally Posted by
Mike Beal
I'm trying.. really hard.. to think of another way....... but i can't.
Alright, I'll take pity.
This is your code from your first post
Code:
#include <iostream>
#include <string>
using namespace std;
int main (){
int answer;
int obama = 0;
int romney = 0;
int option3 = 0;
while (obama < 5 && romney < 5 && option3 < 5)
{
cout<< " who would you like to see become president?\n";
cout<< "1. obama\n2. romney\n3. The bank owns the government.\n";
cin>> answer;
if (answer == 1){
obama++;
}
else if (answer == 2){
romney++;
}
else if (answer == 3){
option3++;
}
else {
cout<< "please enter a number 1-3\n";
}
}
cout<< "obama- " << obama << "\n";
cout<< "romney- " << romney << "\n";
cout<< "doesn't matter- " << option3 << endl;
cin.ignore ();
cin.get ();
}
Now, compare it with my version. What does it do that your code does not (other than some minor changes of what the program outputs, and that I've removed the cin.get()/cin.ignore() closing)? How easy it it to extend?
Code:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main ()
{
vector<string> label;
label.push_back("obama"); // Add strings to label to enable options
label.push_back("romney");
label.push_back("doesn't matter");
size_t i, size = label.size();
vector<int> result(size, 0);
while (*max_element(result.begin(), result.end()) < 5)
{
cout<< "Who would you like to see become president?\n";
for (i = 0; i < size; ++i) cout<< (i + 1) << ". " << label[i] << '\n';
size_t answer;
cin >> answer;
if (answer <= 0 || answer > size)
cout<< "Invalid input. Please enter a value in the range 1-" << size << '\n';
else
++result[answer-1];
}
for (i = 0; i < size; ++i) cout<< label[i] << "- " << result[i] << '\n';
}
Now, okay, I've used a few things from the standard library you probably don't know about yet. But this could be adapted to not use the standard library (other than for output to cout). Instead of a vector of strings, for example, it is possible to use an array of char *.
I haven't even gone out of my way to optimise this code. For example, I have not eliminated unnecessary variables, and have not bothered to break the code up into separate functions, which could make the code even simpler.
I would also personally remove the "using namespace std;" directive (and use std::cout rather than cout) but that's a discussion for another day.