I'm trying to write an if/else statement that says 'if the the random question chosen is the first in the array do this ....' etc for all the members of the array. However it is defaulting every question chosen as the first member of the array and carrying out that action. How can I get it to separate that?
if (choice == 1)
{
enum fields{ QUESTS, ANS_1, ANS_2, ANS_3, ANS_4, NUM_FIELDS };
string QUEST[NUM_QUEST][NUM_FIELDS] =
{
{ "What course is this?\n", "A)C++\n", "B)DID\n", "C)Intro to Game\n", "D)Yoga" },
{ "Who am I?\n", "A)Bill\n", "B)Nye\n", "C) 24601\n", "D)No one\n" },
{ "Are you actually reading this?\n", "A) Yes\n", "B)No\n", "C)Maybe\n", "D)Who wants to know?\n" },
{ "Will this program work?\n", "A)Of course it will!\n", "B)It might\n", "C)Are you kidding me?\n", "D)Gods only know." },
{ "Where would I rather be?\n", "A)Home\n", "B)Europe\n", "C)Anywhere but here\n", "D)All of the above\n" }
};
srand(static_cast<unsigned int>(time(0)));
int randomQuest = (rand() % NUM_QUEST);
string question = QUEST[randomQuest][QUESTS];
cout << question;
string printAns1 = QUEST[randomQuest][ANS_1];
string printAns2 = QUEST[randomQuest][ANS_2];
string printAns3 = QUEST[randomQuest][ANS_3];
string printAns4 = QUEST[randomQuest][ANS_4];
cout << printAns1;
cout << printAns2;
cout << printAns3;
cout << printAns4;
cout << "\nAnswer:";
string answer;
cin >> answer;
//PROBLEM IS HERE. KEEPS DEFAULTING TO THIS IF STATEMENT AND IGNORING THE REST SO THAT IT THINKS THE ANSWER IS ALWAYS A
if (question == QUEST[randomQuest][0])
{
if (answer == "A")
{
cout << "Correct. Proceed.";
}
else if (answer != "A")
{
cout << "Failure. Leave. Or, you know, try again.";
}
}
else if (question == QUEST[randomQuest][1])
{
if (answer == "C")
{
cout << "Correct. Proceed.";
}
else if (answer != "C")
{
cout << "Failure. Leave. Or, you know, try again.";
}
}
else if (question == QUEST[randomQuest][2])
{
if (answer == "D")
{
cout << "Correct. Proceed.";
}
else if (answer != "D")
{
cout << "Failure. Leave. Or, you know, try again.";
}
}
else if (question == QUEST[randomQuest][3])
{
if (answer == "C")
{
cout << "Correct. Proceed.";
}
else if (answer != "C")
{
cout << "Failure. Leave. Or, you know, try again.";
}
}
else if (question == QUEST[randomQuest][4])
{
if (answer == "D")
{
cout << "Correct. Proceed.";
}
else if (answer != "D")
{
cout << "Failure. Leave. Or, you know, try again.";
}
}
}
You did not post the full source, so I just posted an example of how I would do this. Even thought it has a few more lines, its much more readable IMHO.
#include <stdio.h>
#include <vector>
#include <string>
struct Question
{
unsigned char answer;
std::string title;
std::vector<std::string> options;
};
int main()
{
std::vector<Question> questions;
// Define the questions
Question questionOne;
Question questionTwo;
Question questionThree;
Question questionFour;
Question questionFive;
questionOne.answer = 'c';
questionOne.title = "What course is this?";
questionOne.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionOne.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionOne.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionOne.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionTwo.answer = 'a';
questionTwo.title = "Who am I?";
questionTwo.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionTwo.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionTwo.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionTwo.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionThree.answer = 'b';
questionThree.title = "Are you actually reading this?";
questionThree.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionThree.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionThree.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionThree.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFour.answer = 'c';
questionFour.title = "Will this program work?";
questionFour.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFour.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFour.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFour.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFive.answer = 'd';
questionFive.title = "Where would I rather be?";
questionFive.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFive.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFive.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
questionFive.options.push_back("aaaaaaaaaaaaaaaaaaaaaaaaaaa");
// Save them
questions.push_back(questionOne);
questions.push_back(questionTwo);
questions.push_back(questionThree);
questions.push_back(questionFour);
questions.push_back(questionFive);
// Change to a random question accordingly
for (auto& question : questions)
{
// Show question title
std::cout << question.title << std::endl;
// Show question options
for (auto& option : question.options)
{
std::cout << option << std::endl;
}
// Get the user input accordingly
unsigned char userInput = 0;
// Validate user input
if (userInput == question.answer)
{
std::cout << "Congratulations! Next question coming up..." << std::endl;
}
else
{
std::cout << "Wrong answer. Next question coming up..." << std::endl;
}
}
return 0;
}
Related
So I basically have to create a small quiz however I'm unsure on how i would re ask the question I would use when the answer is wrong. I believe its a loop but I'm lost on which one. This is what I have so far
#include <iostream>
using std::cin;
using std::cout;
int main() {
std::string answer;
cout << "Is K before T in the alphabet ?";
cin >> answer;
if (answer == "y") {
cout << "Well done!";
}
else {
cout << "Try again";
}
You could do something like this with a simple boolean control variable:
int main()
{
std::string answer;
bool isCorrect = false;
while(isCorrect == false)
{ std::cout << "Is K before T in the alphabet ?";
std::cin >> answer;
if (answer == "y")
{
isCorrect = true;
std::cout << "Well done!";
}
else
{
std::cout << "Try again";
}
}
}
If you plan on having several questions, you can create a helper function and then call it for each question:
bool inputValidation(std::string strQuestion, std::string strAnser) {
std::string userInput;
std::cout << strQuestion;
std::cin >> userInput;
while (true) {
if (userInput == strAnswer)) {
return true;
}
else {
std::cout << strQuestion;
std::cin >> userInput;
}
}
}
int main() {
bool correct = InputValidation("What is the answer?","42");
correct = InputValidation("Is K before T in the alphabet?", "yes");
}
Then you can put all your questions and answers in a map and use a for each loop to cycle through each question-answer pair. If you need multiple outputs, say, "y" == "Yes" == "1", you can pass a vector<std::string> as the answer.
I have only taken one C++ class and am planning on filling my grandma's children's names with different stuff, what I have currently is just filler. However when I try to debug myself by changing string type to integer like it tells me to I then just get new error codes. Here is what I have currently, the program is quite simple:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
string name;
string main() {
bool done = false;
while (!done) {
cout << "Enter one of your children's names, or press 'q' to quit" << endl;
cin >> name;
if (name = "q") {
done = true;
break;
}
else if (name = "Jason") {
cout << "Jason is your eldest son" << endl;
}
else if (name = "Aaron") {
cout << "Aaron was your second child" << endl;
}
else if (name = "Mandy") {
cout << "Mandy is your only girl" << endl;
}
else if (name = "Adam") {
cout << "Adam came after Mandy" << endl;
}
else if (name = "Ben") {
cout << "Ben is your youngest" << endl;
}
else {
cout << "That name does not exist for your children: try Jason, Aaron, Mandy, Adam, or Ben instead" << endl;
}
}
}
On your if and else if statement you need to change == instead of = (assignment) in order to check if the values of two operands are equal or not.
Also, in your String main() I would recommend to change it for just: int main()
Just to reiterate what everyone else has mentioned
Adjust your if/else compare operator ---> if (name == "q")
Use int main()
int main()
{
bool done = false;
string name;
while (!done)
{
if (name == "q")
{
done = true;
break;
}
// Remainder of code goes here
} // Close while loop
} // Close main()
So i'm making a text adventure game and I want to be able to have a function which has all the inputs in it. So instead of every time me making an if statement to check for every direction I can just put a function that has all of that in it. How do I make this?
string input;
while (input != "n", "s", "e", "w")
{
getline(cin, input);
if (input == "n")
{
dTable();
}
if (input == "e")
{
cout << "You sit on the sofa. Congratulations" << endl;
}
if (input == "w")
{
cout << "You just ran into a wall" << endl;
}
if (input == "s")
{
outsideHouse();
}
if (input == "stats")
{
stats();
}
if (input == "help")
{
help();
}
else
{
cout << "Sorry I am not Siri I don't understand" << endl;
getline(cin, input);
}
break;
}
return 0;
}
You see different approaches of using functions in here,
thats how I would solve this.
You can focus on adding new questions in the main() part and doesn't have to write
all the if-requests over and over.
#include <iostream>
#include <string>
using namespace std;
void help();
void stats();
string check(string input,string n,string s, string w, string e)
{
string result;
if (input == "n"){
result = n;}
else if (input == "s"){
result = s;}
else if (input == "w"){
result = w;}
else if (input == "e"){
result = e;}
else if (input == "help"){
cout << "help" << endl;} //help()
else if (input == "stats"){
cout << "stats" << endl;} // stats()
else if (input == "exit"){
result = "exit";}
else
cout << "Sorry I am not Siri I don't understand. Try again" << endl;
return result;
}
string call()
{
string input;
cout << "Where do you want to go? n s w e" << endl;
getline(cin, input);
return input;
}
int main()
{
bool slope = false;
string input, result;
input = call();
result = check(input,"outside","dTable", "You just ran into a wall", "You sit on the sofa. Congratulations");
while (slope != true)
{
if(result == "house")//room1
{
cout << "You are in the house" << endl;
input = call();
result = check(input,"outside","dTable", "You just ran into a wall", "You sit on the sofa. Congratulations");
}
else if(result == "outside")//room2
{
cout << "You are outside"<< endl;
input = call();
result = check(input,"You just ran into a wall", "house","dTable", "You sit on the sofa. Congratulations");
}
else if(result == "dTable")//room3
{
cout << "You are dTable" << endl;
input = call();
result = check(input,"You just ran into a wall", "You sit on the sofa. Congratulations","outside","house");
} ///adding one room after another and connect it with each other
else if(result == "exit")
{
slope = true;
}
else
{
cout << result << endl;
input = call();
//some winning or loosing message here
}
}
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
bool getAnswer(int a);
int main ()
{
string questions[5] = {"CPU stands for 'Central Processing Unit'", "RAM stands for 'Reserved Access Main'", "HDD stands for 'Hard Drive Doubler'", "SSD stands for 'Solid State Drive'", "CPP stands for 'C Programming Plus'"};
for (int i = 0; i < 5; i++)
{
cout << "Question " << ++i << " \n";
i--;
cout << questions[i] << "\n";
cout << getAnswer(i) << endl;
}
}
bool getAnswer(int a)
{
bool answer[5] = {true, false, false, true, false};
bool user[5];
string input;
cout << "Answer " << ++a << " \n";
a--;
cout << "Enter a true or false answer: " << "\n";
cin >> input;
while (input != "T" && input != "t" && input != "F" && input != "f" && input != "True" && input != "true" && input != "False" && input != "false")
{
cout << "Invalid entry, try again!\nEnter a true or false answer: " << "\n";
cin >> input;
}
if (input == "T" || input == "t" || input == "True" || input == "true")
{
user[a] = true;
}
else if (input == "F" || input == "f" || input == "False" || input == "false")
{
user[a] = false;
}
if (answer[a] == user[a])
{
cout << "Correct!\n";
}
else if (answer[a] != user[a])
{
cout << "Incorrect!\n";
}
}
In the output between the correct/incorrect and next question, I keep getting a "0" in-between. How do i remove them.
Ex:
Question 1
CPU stands for 'Central Processing Unit'
Answer 1
Enter a true or false answer:
f
Incorrect!
0
Question 2
RAM stands for 'Reserved Access Main'
Answer 2
Enter a true or false answer:
t
Incorrect!
0
Just remove cout << "correct" and cout << "incorrect" and change the return type from bool to std::string.
From:
bool getAnswer(int a) {
...
if (answer[a] == user[a])
cout << "Correct!\n";
else if (answer[a] != user[a])
cout << "Incorrect!\n";
}
To:
std::string getAnswer(int a) {
...
if (answer[a] == user[a])
return "Correct!\n";
else if (answer[a] != user[a])
return "Incorrect!\n";
}
What happens in you program is that your function prints on the screen the answer (as that is what your function does inside the last two ifs). After that, your program tries to print what your function returns through:
cout << getAnswer(i) << endl;
Now, you declared the return value of getAnswer()to be of type bool but, actually, you did not specified a return statement. Consequently, the value returned by your function can be either 1 or 0 (undefined behaviour), in your case it is 0, the value you see.
Tip
Use std::cout instead of cout. See Why is “using namespace std” considered bad practice?
You declared getAnswer() to return a bool value, but never return anything. One way to fix your output is to honor this return type and change
if (answer[a] == user[a])
{
cout << "Correct!\n";
}
else if (answer[a] != user[a])
{
cout << "Incorrect!\n";
}
to
return answer[a] == user[a];
Then instead of
cout << getAnswer(i) << endl;
do
if (getAnswer(i)) {
cout << "Correct!\n" << endl;
} else {
cout << "Incorrect\n" << endl;
}
your problem lies with the return value of the getAnswers
cout << getAnswer(i) << endl;
you are already outputting if the answer is correct or not within the getanswer function. and again you are using cout to output the return value of the getAnswer
you can either :
cout << "Question " << ++i << " \n";
i--;
questions[i]
getAnswer(i);
cout << endl;
or you can simply stop doing the output in getAnswer and return a string to containing the message.
std::string getAnswer(int a)
{
bool answer[5] = {true, false, false, true, false};
bool user[5];
string input;
...
...
...
if (answer[a] == user[a])
{
input = "Correct!\n";
}
else if (answer[a] != user[a])
{
input = "Incorrect!\n";
}
return input;
}
if you do it like that you don't need to change anything in your main. make sure to change the decleration of the getAnswers from
bool getAnswer(int a);
to
std::string getAnswer(int a);
I am trying to use 2 different arrays 1 for questions and the for answers but when I select the correct answer for any of the selected questions past "2" it always gives me incorrect answer and I cant see why can anyone held me please?
#include "Questions.h"
using namespace std;
//struct quiz
//{
// string question[MAXITEMS];
// string answers[MAXITEMS];
//};
const int MAXITEMS = 10;
int main ()
{
//quiz listQuiz[MAXITEMS];
//
//ifstream QuestionFile("Questions2.txt");
//char a;
//int count = 0;
//
// if(!QuestionFile) // file testing
// {
// cout<< " error opening file" << endl;
// return 1;
// }
//
// for (int i=0; i<MAXITEMS; i++)
// {
// QuestionFile>>listQuiz[i].
//return 0;
string question[MAXITEMS] = {"How_many_cards_of_each_suit_are_there?", "How_many_suits_are_there_in_a_standard_pack_of_cards?", "How_many_kings_are_in_a_standard_pack_of_cards?", "How_many_cards_are_in_a_standard_deck_of_cards?","How_many_black_suits_are_there_in_a_standard_pack_of_cards?", "How_many_red_suits_are_in_a_standard_pack_of_cards?", "Whats_the_number_of_the_card_that_comes_before_jack?", "How_many_cards_in_each_set_of_suits_are_there?", "What_is_the_lowest_number_in_a_standard_pack_of_cards?", "What_is_the_highest_number_in_a_standard_pack_of_cards?"};
string answers[MAXITEMS] = {"4", "4", "4", "52", "2", "2", "10", "13", "2", "10"};
int userInput = 0;
int tries = 0;
bool isGameOver = false;
cout << "select 1 to start game" << endl; //gives option to start and quit game
cout << "select 2 to quit game" << endl;
cin >> userInput;
if (userInput == 2)
{
isGameOver = true;
return 0;
};
// error message if 1 or 2 is not input
do
{
if (userInput!=1 && userInput!=2)
{
cout << " Your input is not valid! please try again:" << endl; // try switch cases for the different outcomes
cout << "select 1 to start game" << endl;
cout << "select 2 to quit game" << endl;
cin >> userInput;
if (userInput == 2)
{
isGameOver = true;
return 0;
};
while (!(cin >> userInput))
{
cin.clear(); // clear the error flags
cin.ignore(INT_MAX, '\n'); // discard the row
cout << "Your input is not valid! please try again: ";
cout << "select 1 to start game" << endl;
cout << "select 2 to quit game" << endl;
}
cout << userInput << endl;
}
// reprisent all characters as number to stop while roblem
// when game starts gives option to select question and shows all questions
if(userInput == 1)
{
// // system("pause");
// //return-1;
//// };
// while(QuestionFile) // while read is working
// {
//
// // for display
//QuestionFile >> question[count]; // read into array
//cout << count << " " << question << endl;
// count++;
// }
//
// for (int i = 0; i < count ; ++i)
// {cout << " array" << i << " is ::";
// cout << question[i]<< endl;
// }
// cout << question[0]; //reads data in cell
// //QuestionFile.close();
// //system ("pause");
do
{
cout << "select question" << endl;
for(int i = 0; i != MAXITEMS; i++)
{
cout << i << " " << question[i] << endl;
}
int selectQestion;
cin >> selectQestion;
if(selectQestion == 0||1||2||3||4||5||6||7||8||9 && tries != 2)
{
cout << "Enter your answer" << endl;
string userAnswer;
cin >> userAnswer;
while (!(cin >> userAnswer))
{
cin.clear(); // clear the error flags
cin.ignore(INT_MAX, '\n'); // discard the row
cout << "Your input is not valid! please try again: ";
}
if (userAnswer == answers[0])
{
cout << "Correct answer" << endl;
}
else{
cout << "incorrect try again" << endl;
tries++;
cin >> userAnswer;
if (userAnswer == answers[0])
{
cout << "Correct answer" << endl;
}
else
cout << "Incorrect" << endl;
}
}
if (selectQestion == 0||1||2||3||4||5||6||7||8||9 && tries == 2)
{
cout << "you can no longer answer this question" << endl;
cout << "try another question" << endl;
}
}
while(userInput == 1);
}
}
while(isGameOver == false);
}
I'm sure we've been through this before
if (selectQestion == 0||1||2||3||4||5||6||7||8||9 && tries == 2)
is incorrect. This version is correct.
if ((selectQestion == 0 || selectQestion == 1 || selectQestion == 2 || selectQestion == 3 || selectQestion == 4 || selectQestion == 5 || selectQestion == 6|| selectQestion == 7|| selectQestion == 8 || selectQestion == 9) && tries == 2)
But really you should use a little bit of logic and simplify, this version is even better
if (selectQestion >= 0 && selectQestion <= 9 && tries == 2)
Much better.
Fix that problem (you have it in at least two places) and if your program is still not working post again.
This doesn't make sense:
string question[MAXITEMS] = {"How_many_cards_of_each_suit_are_there?",
"How_many_suits_are_there_in_a_standard_pack_of_cards?",
"How_many_kings_are_in_a_standard_pack_of_cards?",
"How_many_cards_are_in_a_standard_deck_of_cards?",
"How_many_black_suits_are_there_in_a_standard_pack_of_cards?",
"How_many_red_suits_are_in_a_standard_pack_of_cards?",
"Whats_the_number_of_the_card_that_comes_before_jack?",
"How_many_cards_in_each_set_of_suits_are_there?",
"What_is_the_lowest_number_in_a_standard_pack_of_cards?",
"What_is_the_highest_number_in_a_standard_pack_of_cards?"};
string answers[MAXITEMS] = {"4", "4", "4", "52", "2", "2", "10", "13", "2", "10"};
To me, the answers and questions aren't in synch. And of course, it would be MUCH easier to deal with this if you have question and answer as part of a struct (or class):
struct QuestionAndAnswer
{
std::string question;
std::string answer;
}
QuestionAndAnswer qAndA[MAXITEMS] =
{
{ "Question 1", "Answer for question 1" },
{ "Question 2", "Answer for question 2" },
...
};
And this code doesn't do what you think it does:
if(selectQestion == 0||1||2||3||4||5||6||7||8||9 && tries != 2)
As suggested in another answer, you could do if (selectOption == 0 || selectOption == 1 ..., but I would suggest that you use a switch statement:
switch(selectOption)
{
case 0:
case 1:
... // more cases go here.
case 9:
if (tries != 2)
...
else // tries == 2
...
break;
default:
... Stuff to do when input was not a valid selection.
break;
}
It is much easier to read a switch than a 11 item long if-condition.
A further problem is this:
do {
...
} while(userInput == 1);
The variable userInput isn't changing inside that loop...
You also have a bug here:
if (userAnswer == answers[0])
You probably want to check that the answer is the answer to the selected question, not the first question.
May I suggest that you develop smaller parts of the code at a time - change one little thing, test it, if it doesn't work, figure out why, then write a bit more code. I've not even compiled or run your code, and I've spotted at least four distinct errors that - yes, I've done programming for over 30 years, so I have some experience in spotting errors.
This:
if (selectQestion == 0||1||2||3||4||5||6||7||8||9 ...)
is equivalent to:
if (selectQuestion == 1 ...)
The right hand side of the == sign is an expression for which C++ calculates a value and substitutes that value in place of that long series of ||'s.