Hey guys I'm trying to get back into C++. I'm just experimenting with a program I created. I'm trying to get the user to answer a few questions in an assigned quiz. I'm having trouble using the loop to label each question with a number (1,2,3,4,5) and at the same time have a different question assigned to each. For question #1 I would like to have it ask "how old are you?"
For question #2: Do you own property? For question #3: Do you operate a motor vehicle? You get the idea, just messing around and experimenting with totally bogus made up questions. Also in the earlier part of my code I would like to end the program after the user enters "no". How could I do that as well? Thanks!
//Practice
#include <iostream>
#include <string>
usingnamespace std;
int main ()
{
int x, i;
string response;
cout << "Please enter a number (1 or 2)" << endl;
cin >> x;
while ( x > 2)
{
cout << "Error!" << endl;
cout << "Please enter (1 or 2)" << endl;
cin >> x;
}
if (x == 1)
cout << "Congrats! You have been entered for a chance to win $100!" << endl;
elseif (x == 2)
cout << "Congrats! You have been entered for a chance to win an Ipod!" << endl;
cout << "Are you ready to take a short quiz for a chance to win?" << endl;
cout << "Please answer (yes or no)" << endl;
cin >> response;
cout << "You answered " << response << endl;
if (response == "yes")
cout << "Thanks for taking part in the quiz!" << endl;
elseif (response == "no")
cout << "No problem, now exiting." << endl;
for (i=1; i<6; i++)
{cout << "Question" << i << ":" << "how old are you?" << endl;
}
system("pause");
return 0;
}
If I was to do it, I would write all my questions into a different string (globally) and then write a quick function for the numbering at the beginning of the line, and write a separate function to display each question. Using a compare statement for i in the previous function, it would display a certain question.
So like :
1 2 3 4 5 6 7 8 9 10
int i = 0
int counter(){
Int begin = 0;
while(begin <= 5){
cout >> i ": " << question();
i++;
}
Do you think you could show a general example of this? I tinkered around but the function didn't want to work when I placed it inside cout. I made a function called void questions(); and placed the questions inside of that function.
I tried something like
cout << "Question " << i << ":" << question();
One reason to rewrite the menu utility using a vector is you could randomize the order using an STL algorithm, like std::random_shuffle.
http://www.cplusplus.com/reference/algorithm/random_shuffle/
There is lots of room to improve that code in many ways. ;)