Reaching end of void function yield unexpected results - c++

I wrote a simple program to manage a list of names (a segment of the program is below). I expected the function "choice()" to end and return to main()--and thus end the program--when the user's input for the variable "option" was 4. However, choice() tends to repeat a few times even after assigning 4 to "option", e.g:
Would you like to:
(1) - Add name(s) to the list
(2) - Remove name(s) from the list
(3) - View the list
(4) - Exit the program
(type 1, 2, 3, or 4): 4
Exiting Program...
Would you like to:
(1) - Add name(s) to the list
(2) - Remove name(s) from the list
(3) - View the list
(4) - Exit the program
(type 1, 2, 3, or 4): 4
Exiting Program...
ryan$ _
In the absence of the entire program, what do you think may be causing the problem? Sorry if there is not enough information to make a recommendation.
You can see I commented "exit(0)" from the end of the fourth if statement of choice()--in which choice() should reach its end and return to main(). I would prefer to avoid this statement but it is the only solution I can make work at the moment. Thanks for your help.
-Ryan
int main()
{
cout << endl
<< "WELCOME TO THE NAME LIST PROGRAM" << endl
<< "--------------------------------" << endl;
choice();
return 0;
}
void choice()
{
string option = "0";
cout << "\nWould you like to:" << endl
<< "\t(1) - Add name(s) to the list" << endl
<< "\t(2) - Remove name(s) from the list" << endl
<< "\t(3) - View the list" << endl
<< "\t(4) - Exit the program" << endl
<< "(type 1, 2, 3, or 4): ";
getline(cin,option);
while( option != "1" && option != "2" &&
option != "3" && option != "4" )
{
cout << "\nInvalid input, reenter: ";
getline(cin,option);
}
if(option == "1")
{
appendNames();
choice();
}
else if(option == "2")
{
string flag = "menu";
removeNames(flag);
choice();
}
else if(option == "3")
{
viewNames();
choice();
}
else if(option == "4")
{
cout << "\n\nExiting Program...\n\n";
// exit(0);
}
}

I think the problem comes from a misconception about a how a function works. Say that you have a function that shows your name:
void showName()
{
cout << "Ryan" << endl;
}
Now say that you want to repeat that 10 times. In your particular way of programming, you probably would do something like:
void showName(int times)
{
cout << "Ryan" << endl;
if ( times > 0 ) {
showName( --times );
}
return;
}
int main()
{
showName( 10 );
}
This way of programming is known as recursion, but I am quite sure that you have reached that by chance. Recursion is handy in some situations, but it is not the common way of doing simple things, like repeating something. Let's see the actual program calling the function 10 times:
void showName()
{
cout << "Ryan" << endl;
}
int main()
{
for(int i = 0; i < 10; ++i) {
showName();
}
}
Each time you call the function showName(), the callee, it has to return to the caller. If you do what you have shown in your example:
if( option == "1" )
{
appendNames();
choice();
}
Then you are actually calling choice() as many times as the user has chosen any other option apart from 4 (exit). This explains why you have to call exit( 0 ) in order to get an immediate effect.
Summarizing, your program should be:
int main()
{
cout << endl
<< "WELCOME TO THE NAME LIST PROGRAM" << endl
<< "--------------------------------" << endl;
while( !choice() );
return 0;
}
bool choice()
{
bool toret = false;
string option = "0";
cout << "\nWould you like to:" << endl
<< "\t(1) - Add name(s) to the list" << endl
<< "\t(2) - Remove name(s) from the list" << endl
<< "\t(3) - View the list" << endl
<< "\t(4) - Exit the program" << endl
<< "(type 1, 2, 3, or 4): ";
getline(cin,option);
while( option != "1" && option != "2" &&
option != "3" && option != "4" )
{
cout << "\nInvalid input, reenter: ";
getline(cin,option);
}
if(option == "1")
{
appendNames();
}
else if(option == "2")
{
removeNames();
}
else if(option == "3")
{
viewNames();
}
else if(option == "4")
{
cout << "\n\nExiting Program...\n\n";
toret = true;
}
return toret;
}
Hope this helps.

The problem is in your while loop. The user will have to keep entering inputs until an invalid input it given.
while( option != "1" && option != "2" &&
option != "3" && option != "4" )
{
cout << "\nInvalid input, reenter: ";
getline(cin,option);
}
Changing the loop condition or moving everything within the loop should do the trick.
Hope that helps. :)
P.S: If you're moving everything within the While loop, make sure you add a break; for the exit option.

Related

calling function on while loop

I'm making a calculator program but I already encounter a problem. Well, my code is in a loop that will call a function to display the choices and then ask the user to pick, a/s/m/d are the choices. If the input is on the choices, it will proceed to the next step. Otherwise, it will loop and then call the function again.
#include <iostream>
using namespace std;
void home()
{
cout << "\nChoose your operation:" << endl;
cout << "\tType [A] for Addition" << endl;
cout << "\tType [S] for Subtraction"<< endl;
cout << "\tType [M] for Multiplication" << endl;
cout << "\tType [D] for Division" << endl;
}
int main()
{
char operation;
bool no_operator = true;
int design = 73;
for (int i = 0; i < design; i++){
if (i == 25){
cout << " WELCOME TO CALCULATOR ";
i += 22;
}
else i == 72 ? cout << "*\n" : cout << "*";
}
while (no_operator){
home();
cout << "\nOperation: ";
cin >> operation;
if (operation == 'A' || operation == 'a')
{
cout << "\nIt will going to add numbers";
no_operator = false;
}
else if (operation == 'S' || operation == 's')
{
no_operator = false;
cout << "\nIt will going to subtract numbers";
}
else if (operation == 'M' || operation == 'm')
{
no_operator = false;
cout << "\nIt will going to multiply numbers";
}
else if (operation == 'D' || operation == 'd')
{
no_operator = false;
cout << "\nIt will going to divide numbers";
}
else
{
cout << "\tInvalid Input: You must enter A/S/M/D only\n";
//home();
}
}
return 0;
}
My problem is it will run the '''home()''' in else statement even if the input is correct on the second loop.
I want to stop the '''home()''' to be called when the input is correct
Your code works perfectly fine. Make sure you're inputting the correct letters.
Also for this code, a "do while()" loop would be better.
You program is working perfectly fine as the input is correct it does not show the home rather print the message it will going to divide etc.

Can someone help me figure out why my code isn't working properly?

#include <iostream>
using namespace std;
int fight();
int lowblow();
int eyes();
int run();
int underground();
int officebuilding();
int main()
{
int choice1;
int fchoice2, fchoice3;
int rchoice2, rchoice3;
cout << "As you’re walking down the street you feel somebody grab your shoulder, when you turn around to see. You notice the person is holding a knife towards you and demanding for your valuables." << endl;
cout << "Do you fight or run?" << endl;
cout << "1 - Fight" << endl;
cout << "2 - Run" << endl;
cin >> choice1;
while (choice1 != 1 && choice1 != 2) {
cout << "Do you fight or run? " << endl;
cout << "1 - Fight" << endl;
cout << "2 - Run" << endl;
cin >> choice1;
}
if (choice1 == 1) {
fchoice2 = fight();
while (fchoice2 != 1 && fchoice2 != 2) {
fchoice2 = fight();
}
if (fchoice2 == 1) {
fchoice3 = lowblow();
while (fchoice3 != 1 && fchoice3 != 2) {
fchoice3 = lowblow();
}
}
if (fchoice2 == 2) {
fchoice3 = eyes();
while (fchoice3 != 1 && fchoice3 != 2) {
fchoice3 = eyes();
}
if (choice1 == 2) {
rchoice2 = run();
while (rchoice2 != 1 && rchoice2 != 2) {
rchoice2 = run();
}
if (rchoice2 == 1) {
rchoice3 = underground();
while (rchoice3 != 1 && rchoice3 != 2) {
rchoice3 = underground();
}
if (rchoice3 == 1) {
officebuilding();
}
}
}
}
}
}
int fight()
{
system("clear");
int c2;
cout << "You choose to fight off the attacker and suddenly all those self-defense classes come rushing into your mind.As you fight to defend yourself, you find yourself getting outmatched and have to try something drastic to survive." << endl;
cout << "1 - Go for the low blow" << endl;
cout << "2 - Go for the eyes " << endl;
cin >> c2;
return c2;
}
int lowblow()
{
system("clear");
cout << "You catch your attacker off guard and land the hit, to your surprise the attack proves ineffective.In retaliation you get hit so hard that you start seeing stars and soon blackout leaves you defenseless.Now you are knocked out and getting your valuables taken." < endl;
cout << "The End" << endl;
return 0;
}
int eyes()
{
system("clear");
cout << "Using the element of surprise to try fighting back gave you no advantage, so you resort to another tactic. You’ve seen it in movies and it always worked out there. You decide to go for the eyes and to your surprise it works. You use this opportunity to escape and get to safety, all while keeping your valuables safe. "<< endl;
cout << "The End" << endl;
return 0;
}
int run()
{
system("clear");
int c2;
cout << " While running down the street to loose the attacker, you noticed that there was an underground subway a little down the road.Immediately to your left there is an office building you could run into and try to lose your attacker there."<< endl;
cout << "1 - Underground ?" << endl;
cout << "2- office building?" << endl;
cin >> c2;
return c2;
}
int underground()
{
system("clear");
cout << "As you make your way towards the underground subway station you notice rushing out.In a desperate attempt to reach safety, you run down the stairs while narrowly avoiding others.Upon arriving at the station you look back and notice that you lost your attacker.You are safe now.";
cout << "The End" << endl;
return 0;
}
int officebuilding()
{
system("clear");
cout << "A spontaneous decision leads you into an office building, while it may look safe, upon entering you notice everything is silent as the building seems to be completely empty.None of it matters however, since you have to escape at any cost in order.While trying to find a good way to lose the attacker you hear footsteps behind you.The attacker has cornered you and has taken your valuables." << endl;
cout << "The End" << endl;
return 0;
}
I am suppose to be writing a branching-path story. I am not sure why after I pick a choice it starts flashing and for the other choice it isn't even working. I'm not exactly sure where to fix these errors in the code. I'm not sure if I messed up somewhere in the functions or while loop. I've tried changing some things around but nothing seems to work.
You are calling underground() in a while-loop waiting for rchoice3 to be 1 or 2, but underground() always returns 0, so rchoice3 is always 0..
while (rchoice3 != 1 && rchoice3 != 2) {
rchoice3 = underground();
}
I think you need to change this block:
if (rchoice2 == 1) {
rchoice3 = underground();
while (rchoice3 != 1 && rchoice3 != 2) {
rchoice3 = underground();
}
if (rchoice3 == 1) {
officebuilding();
}
}
To:
if (rchoice2 == 1) {
underground();
} else {
officebuilding();
}

C++ Homework Doesn't Loop

So, I'm super new to C++ and am sharing a book with a friend. I'm creating a simple guessing game, where the user imagines a number, and the computer attempts to guess it. When I debug in Visual Studio, the project does make a guess, and properly prints "how did I do?". At this point, it should get user input for the 'feedback' variable. After the prompt, however, it seems as if it will only repeat everything before the 'while' statement. Does the problem concern the feedback char variable (maybe I should've just used 'cin' and integers?), or am I just missing something really obvious?
//Game that attempts to guess a number from one to twenty.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
auto lowbound = 1;
auto highbound = 20;
auto guess = 10;
auto gamecont = true;
char feedback[1];
cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << endl << endl;
cout << " If my guess is too low, just say (1). If too high, say (2). Say (3) if I've got it. It's (ENTER) to get going!" << endl << endl;
cout << " Waiting on you..." << endl << " ";
cin.get();
while(gamecont)
{
cout << " I'm thinking your number is " << guess << "." << endl << endl;
cout << " How did I do?" << endl << endl << " ";
cin.get(feedback, 1);
if (feedback[1] == 1) // The guess was too low.
{
if (guess == 10)
{
guess = 15;
}
else if (guess >= 15)
{
guess++;
}
else if (guess < 10)
{
guess++;
}
}
else if (feedback[1] == 2) // The guess was too high.
{
if (guess == 10)
{
guess = 5;
}
else if (guess <= 5)
{
guess--;
}
else if (guess > 10)
{
guess--;
}
}
else if (feedback[1] == 3) // The guess was correct.
{
gamecont = false;
}
}
return 0;
}
Sorry if this question is stupid for whatever reason, and thanks in advance for reading.
a journey of a thousand miles begins with a single step, so here´s some aid for your first step:
using namespace std;
don´t do that. std:: is crowded with identifiers you might use too, problems are guaranteed.
char feedback[1];
You´ll never have input longer than 1, so
char feedback;
is more than appropriate. (besides: arrays are 0 based so it should have been char feedback[0]; instead of char feedback[1];)
cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << endl << endl;
std::endl flushes the buffer, no need to do that twice. Simply use '\n':
std::cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << "\n\n";
you´ll get the character code of the key in feedback. '1' is not equal to 1, so
if (feedback == 1)
should be
if (feedback == '1')
Thats it. There still some work remaining to do for you, e.g. the guessing strategy is poor, but that should be a start.
//Game that attempts to guess a number from one to twenty.
#include <iostream>
int main()
{
auto lowbound = 1;
auto highbound = 20;
auto guess = 10;
auto gamecont = true;
char feedback;
std::cout << " Pick a number from one to twenty in you head and I'll guess it; no cheating!" << "\n\n";
std::cout << " If my guess is too low, just say (1). If too high, say (2). Say (3) if I've got it. It's (ENTER) to get going!" << "\n\n";
std::cout << " Waiting on you..." << "\n\n";
std::cin.get();
while(gamecont)
{
std::cout << " I'm thinking your number is " << guess << "." << "\n\n";
std::cout << " How did I do?" << "\n\n";
std::cin.ignore();
std::cin.get(feedback);
if (feedback == '1') // The guess was too low.
{
if (guess == 10)
{
guess = 15;
}
else if (guess >= 15)
{
guess++;
}
else if (guess < 10)
{
guess++;
}
}
else if (feedback == '2') // The guess was too high.
{
if (guess == 10)
{
guess = 5;
}
else if (guess <= 5)
{
guess--;
}
else if (guess > 10)
{
guess--;
}
}
else if (feedback == '3') // The guess was correct.
{
gamecont = false;
}
}
return 0;
}

Fixing else if statements in a for loop c++

So I'm working on a little bit of a project involving AI, and I have run into a problem. The program should use a for loop to search the index of common known phrases, and if they don't match the sentence, then in the else statement it figures out which sentence model to apply, then generates output using that sentence model. Here are the built in phrases, they are stored in arrays:
string greetings[6] = {"hey", "hello", "hi", "hey max", "hello max", "hi max"};
string howsItGoing[6] = {"hows it going?","how's it going max?","hows it going max?", "whats up?", "whats up max?"};
string whatsYourName[6] = {"whats your name?", "what's your name?" , "whats your name max?", "what's your name max?"};
string dogsOrCats[6] = {"do you like dogs or cats?", "do you like cats or dogs?", "which do you like more cats or dogs?", "which do you like more dogs or cats?"};
string areYouAlive[6] = {"hey max are you alive?", "hey are you alive?", "max are you alive?", "are you alive?"};
string favoriteColor[6] = {"whats your favorite color?", "what's your favorite color?", "what is your favorite color?", "max whats your favorite color?", "max what's your favorite color?", "max what is your favorite color?"};
string whatGender[6] = {"are you a boy or a girl?", "are you boy or girl?", "are you a guy?", "max are you a boy or girl?", "max are you a guy?", "are you a boy or girl?"};
(This is a temporary method, I'm devising a little thing called a Sentence Decoder that will eventually replace all built in phrases.)
So my problem is this: In the for loop, the first if statement can search the entire array and respond with a suitable output, whether the input was greetings[0] or greetings [4]. However, all the else-if statements appear to be just looking for index 0. I believe this has to do with the for loop only searching across the first one 6 times, but I'm mostly likely wrong. I tried increasing the for loop end-number from 6 to 40 to see if that would help, but alas it didn't make a difference. Here is the rest of the code (It's so ugly! I need to make a function for it or something.... but then again, the whole thing itself is a function...
for (int i = 0; i < 6; i++) {
//Checking if it fits in any of the known greetings
if (input == database.greetings[i]) {
if (timesBeenGreeted == 0) {
cout << "Oh, hey." << endl;
timesBeenGreeted++;
break;
}
else if (timesBeenGreeted == 1) {
cout << "hello?" << endl;
timesBeenGreeted++;
break;
}
else if (timesBeenGreeted == 2) {
cout << "You've said hi to me twice now." << endl;
timesBeenGreeted++;
break;
}
else if (timesBeenGreeted >= 3) {
cout << "Stop. It." << endl;
timesBeenGreeted++;
break;
}
i = 0;
continue;
}
else if (input == database.howsItGoing[i]){
if (askedHowsItGoing == 0) {
cout << "Yeah, not bad." << endl;
askedHowsItGoing++;
break;
}
else if (askedHowsItGoing == 1) {
cout << "Um, yeah, I'm good? You've already asked that." << endl;
askedHowsItGoing++;
break;
}
else if (askedHowsItGoing == 2) {
cout << "Alright, look. I already told you I'm fine, two times now." << endl;
askedHowsItGoing++;
break;
}
else if (askedHowsItGoing >= 3) {
cout << "STOP ASKING ME IF IM OKAY!" << endl;
askedHowsItGoing++;
break;
}
continue;
}
else if (input == database.whatsYourName[i]){
if (askedName == 0) {
cout << "My name's Max, and I'm going to become the worlds most advanced AI." << endl;
askedName++;
break;
}
else if (askedName == 1) {
cout << "I already told you, my names Max." << endl;
askedName++;
break;
}
else if (askedName == 2) {
cout << "For the third time, my name is Max!" << endl;
askedName++;
break;
}
else if (askedName >= 3) {
cout << "Ugh... my name.... is.... max....for the fourh time...." << endl;
askedName++;
break;
}
continue;
}
else if (input == database.dogsOrCats[i]) {
if (askedDogsOrCats == 0) {
cout << "I've never seen a dog or cat before. But I do know they are kinds of animals." << endl;
askedDogsOrCats++;
break;
}
else if (askedDogsOrCats == 1) {
cout << "As I've said, I haven't seen either of them before. Sorry, but that's all I can say." << endl;
askedDogsOrCats++;
break;
}
else if (askedDogsOrCats == 2) {
cout << "Uh, for the third time, I've never seen either of them..." << endl;
askedDogsOrCats++;
break;
}
else if (askedDogsOrCats >= 3) {
cout << "Man, you are persistant. I haven't seen dog or cat, so I couldn't choose between the two." << endl;
askedDogsOrCats++;
break;
}
continue;
}
else if (input == database.areYouAlive[i]){
if (askedAlive == 0) {
cout << "Nope, I'm just a computer program. I'm not even that intelligent. But I will be!" << endl;
askedAlive++;
break;
}
else if (askedAlive == 1) {
cout << "Nah, I'm just a simple computer program." << endl;
askedAlive++;
break;
}
else if (askedAlive == 2) {
cout << "Uh, you asked that twice before now. Nothing alive about me." << endl;
askedAlive++;
break;
}
else if (askedAlive == 3) {
cout << "Stop asking me that! No, I'm not!" << endl;
break;
}
continue;
}
else if (input == database.favoriteColor[i]) {
if (askedColor == 0) {
cout << "I've never seen any colors before. All though, my programmer does like the color blue." << endl;
askedColor++;
break;
}
else if (askedColor == 1) {
cout << "Couldn't say, never seen any before. My programmer likes blue though." << endl;
askedColor++;
break;
}
else if (askedColor == 2) {
cout << "As I've said twice before now, never seen any colors." << endl;
askedColor++;
break;
}
else if (askedColor == 3) {
cout << "Come on man, this is the fourth time now. I've never seen any colors before!" << endl;
break;
}
continue;
}
else if (input == database.whatGender[i]) {
if (askedGender == 0) {
cout << "Well, seeing as I'm a computer program, I'm neither really. Although, my programmer says I'm a 'guy'." << endl;
askedGender++;
break;
}
else if (askedGender == 1) {
cout << "I'm neither, really. Although, my name is Max and my programmer says I'm a guy." << endl;
askedGender++;
break;
}
else if (askedGender == 2) {
cout << "Third time you've asked now. My programmer says I'm a guy." << endl;
askedGender++;
break;
}
else if (askedGender == 3) {
cout << "Seriously?! You've asked me 4 times now. I'M A GUY!" << endl;
break;
}
continue;
}
//If it doesnt, check each word against words in the database.
else {
if (inputWords[5] != "") {
Model1 model;
model.searchAndAssign(input, inputTokens, inputWords);
model.generateOutput();
for (int i= 0; i < 20; i++) {
inputWords[i] = "";
}
break;
}
else if (inputWords[2] != "") {
Model2 model2;
model2.searchAndAssign(input, inputTokens, inputWords);
model2.generateOuput();
for (int i= 0; i < 20; i++) {
inputWords[i] = "";
}
break;
}
}
}
My question is this: How can I solve this problem?
Thank you in advanced guys!
EDIT I've since fixed the problem: something was playing up in my main.cpp file (this was the lingusticsModule.cpp file....) that was causing the issue. Sorry guys, but thanks for the help anyway!
At the end of your first if you reset the loop iterator and skip everything else.
i = 0;
continue;
Your else ifs may match but if the increments have been reached, then they just continue which doesn't make much sense. What are you hoping to find?
else if (askedGender == 3) {
cout << "Seriously?! You've asked me 4 times now. I'M A GUY!" << endl;
break;
}
continue;
You find this behavior confusing because it is. It might make more sense to do something like:
else {
++askedGender;
std::cout << "Seriously?! You've asked me "
<< askedGender << " times now. I'M A GUY!\n";
}

Trying to use two diffrent arrays to ask and answer questions

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.