Why won't this C++ While loop work? [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm simply trying to get the user to put in their name/age and verify if it's correct. If not then they get 4 tries before the program will abort. However my while loops don't loop, instead they just continue on to the next loop. I've tried a variation of things inside the while parenthesis (op != 1) (!(op = 1)) etc.
int main() {
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+ 1;
}
if (tries = 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 = 4) {
//abort the programhi
}
}
}
return 0;
}
I'm fairly new to C++ so I'm sorry if it does have a simple answer. But anyway, I've been debugging this for over half an hour and I looked online for 20+ minutes.

if (tries = 4) {
//abort the program
}
Change this to
if (tries == 4) {
//abort the program
}
And
f (op == 2) {
cout << "Please Try Again!";
tries+= 1; // tries+ 1;
}
You can increment value in C++ like this tries+ 1;. Either use tries+= 1; or tries++;

tries+ 1; should be tries += 1; or tries++;
And,
if (tries = 4) {
//abort the program
}
should be:
if (tries == 4) {
//abort the program
}

Your program should look like this:
int main()
{
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+= 1;
}
if (tries == 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 == 4) {
//abort the programhi
}
}
}
You have forget to use = sign at multiple places. tries = 4 should be tries == 4 for comparing variable tries with numeric 4. tries = 4 was reassigning the variable tries to four and your while loop was getting terminated after it's first run. Also, tries + 1 should be tries += 1 or tries++ to increment the value of tries variable by one.

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.

I need help creating a scoring system, but it keeps giving me an error, the commented out integers are the parts giving me trouble

I found an RPS game and wanted to improve on it by creating a scoring system but the //int compwin = compwin + 1; keeps giving me errors. I am still fairly new to coding in C++ and have no clue where the problem is standing so thanks for helping in advance. Also this code was taken from somewhere this is not my code but I wanted to try and improve on it.
#include <iostream>
#include <cstdlib>
#include <limits>
#include <ctime>
#include <string>
using namespace std;
int main()
{
int choice;
int i;
int y;
int Y;
int comp;
char res;
int compwin = 0;
int choicewin = 0;
unsigned seed;
while (1==1) {
//The choices
cout << "Game Choices.\n\n";
cout << "1.Rock\n";
cout << "2.Paper\n";
cout << "3.Scissors\n";
cout << "4.Quit, exits the game.\n\n";
cout << "Please enter your choice.\n\n";
cin >> choice;
//-----------------------Player Imputs-----------------------------------
if (choice == 1) //Rock
{
cout << "You picked Rock.\n";
cout << "Now here was my choice.\n\n";
}
else if (choice == 2) //Paper
{
cout << "You picked Paper.\n";
cout << "Now here was my choice.\n\n";
}
else if (choice == 3) //Scissors
{
cout << "You picked Scissors.\n";
cout << "Now here was my choice.\n\n";
}
else if (choice == 4)
{
return 0;
}
else if (choice != 1 || 2 || 3 || 4) // Debug
{
cout << "Uhhhh thats not one of the following.\n\nGoodbye!\n\n";
system("pause");
return 0;
}
//-------------------------Computer Choice-------------------------------
seed = time(0);
srand(seed); //RNG TIME
comp = rand() % 3 + 1; //Computer picks
if (comp == 1) //Computer rock
{
res = 1;
cout << "Rock!\n\n";
}
else if (comp == 2) //Computer paper
{
res = 2;
cout << "Paper!\n\n";
}
else if (comp == 3) // Computer scissors
{
res = 3;
cout << "Scissors!\n\n";
}
//-----------------------Victory Conditions------------------------------
if (comp == 1 && choice == 1) {
std::cout << "It was a tie!" << endl;
}
else if (comp == 1 && choice == 3) {
std::cout << "I Won! Better luck next time!" << endl;
//int compwin = compwin + 1; This is where the problem occurs
}
else if (comp == 2 && choice == 2) {
std::cout << "It was a tie!" << endl;
}
else if (comp == 2 && choice == 1) {
std::cout << "I Won! Better luck next time!" << endl;
//int compwin = compwin + 1; This is where the problem occurs
}
else if (comp == 2 && choice == 3) {
std::cout << "It was a tie!" << endl;
}
else if (comp == 2 && choice == 2) {
std::cout << "I Won! Better luck next time!" << endl;
//int compwin = compwin + 1; This is where the problem occurs
}
else {
std::cout << "Congrats! You won!" << endl;
//int choicewin = choicewin + 1; This is where the problem occurs
}
cout << "Heres the score, computer =" << compwin << "and player =" << choicewin;
cout << "Want to go again? (y/n)";
cin >> res;
system("cls");
}
while (res == y || Y);
system("pause");
return 0;
}
This
int compwin = compwin + 1;
is a declaration and initialization. A rather weird one, and to discuss why it is allowed would take us on a too big detour. So lets look at a simpler example:
int compwin = 1; // declares compwin and initializes it with 1
int compwin = 2; // compiler error, because compwin is already declared
You can only declare the same variable once (again the long complete truth is more involved, search for "shadowing" in case you care). You also only need to initialize a variable only once.
If you want to assign something to an already declared variable, you use assignment, as in
int compwin = 1; // declare and initialize
compwin = 2; // assign
Further note that
else if (choice != 1 || 2 || 3 || 4) // Debug
is not doing what you expect. The correct way is
else if (choice != 1 && choice != 2 && choice != 3 && choice != 4)
The mistake is a combination of ignoring De Morgan's Law and a wrong combination of several conditions. The operator|| expects a bool on both sides and unfortunately numbers happily convert to true (only 0 becomes false), but a good compiler may spit out warnings on that. Similar mistake is on while (res == y || Y);.

Tic Tac Toe , Why am I getting the error non standard syntax use & to create a pointer to a member [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
here is my main . I get the error for the part I am checking whether the game had a winner or not. the errors are referring to the if parts where i wanna check the returned data from chkwin method
#include<iostream>
#include<string>
#include "TicTacToe.h"
using namespace std;
int main()
{
string choice = "";
string name1 = "";
string name2 = "";
string change = "";
int choice_num;
TicTacToe game;
cout << "Welcome to TicTacToe World!\n"
<< "In order to Start Please Enter the name of the first player\n\n";
getline(cin, name1);
cout << "\nGreat, Now Please Enter the name of the second player\n\n";
getline(cin,
name2);
cout << "\nAwesome Let's Get Started!\n";
do
{
cout << "\nPlease choose what do you want to do by entering the number of your choice\n"
<< "1.Start the game.\n"
<< "2.Change the names.\n"
<< "3.View Scores\n"
<< "4.Exit the Game :(\n\n";
getline(cin, choice);
if (choice == "1")
{
for (int i = 1; 1 <= 9; i++)
{
if (i % 2 != 0)
{
cout << "It's " << name1 << " Turn. Please Make Your move.";
cin >> choice_num;
cin.ignore();
game.setMove(choice_num, 1);
if (game.chkWin == 1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == -1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == 0)
{
cout <<"The Game is a Draw! ";
}
}
else
{
cout << "It's " << name1 << " Turn. Please Make Your move.";
cin >> choice;
cin.ignore();
game.setMove(choice_num, 2);
if ( 1 == game.chkWin)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == -1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == 0)
{
cout << "The Game is a Draw! ";
}
}
}
}
else if (choice == "2")
{
do
{
cout << "\nwhich player do you want its name to be changed? (Enter 1 for the first, 2 for the second and 3 for both)\n";
getline(cin, change);
if (change == "1")
{
cout << "\nPlease Enter the new name for the player one.\n";
getline(cin, name1);
}
else if (change == "2")
{
cout << "\nPlease Enter the new name for the player two.\n";
getline(cin, name2);
}
else if (change == "3")
{
cout << "\nPlease Enter the new name for the player one.\n";
getline(cin, name1);
cout << "\nPlease Enter the new name for the player two.\n";
getline(cin, name2);
}
else
{
cout << "\nPlease Enter a Valid Choice.\n";
}
} while (change != "1" && change != "2" && change != "3");
}
else if (choice == "3")
{
cout << "\n" << game.getResults(name1, name2);
}
else if (choice != "4")
{
cout << "\nPlease Enter a Correct number\n";
}
} while (choice!= "4");
cout << "\nFinal Results are: \n\n"
<< game.getResults(name1, name2);
cout << "\nThank you for using our program. Hope to see You Again. Bye Bye!!\n";
system("Pause");
return 0;
}
my class
#include<iostream>
#include<string>
using namespace std;
#ifndef TICTACTOE_H
#define TICTACTOE_H
class TicTacToe
{
private:
const static int SIZE = 3;
int table[SIZE][SIZE];
int results[SIZE];
int winner = 2;
public:
TicTacToe();
void setMove(int , int );
int chkWin();
string getResults(string , string );
};
#endif
here is my methods declaration:
#include<iostream>
#include<string>
#include "TicTacToe.h"
using namespace std;
TicTacToe::TicTacToe()
{
for (int i = 0; i < SIZE; i++)
{
results[i] = 0;
for (int j = 0; j < SIZE; j++)
{
table[i][j] = 0;
}
}
}
void TicTacToe::setMove(int place, int player)
{
int field = place;
if (field == 1)
{
if (table[0][0] == 0)
{
table[0][0] = player;
}
else
{
cout << "\nYou cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 2)
{
if (table[0][1] == 0)
{
table[0][1] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 3)
{
if (table[0][2] == 0)
{
table[0][2] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 4)
{
if (table[1][0] == 0)
{
table[1][0] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 5)
{
if (table[1][1] == 0)
{
table[1][1] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 6)
{
if (table[1][2] == 0)
{
table[1][2] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 7)
{
if (table[2][0] == 0)
{
table[2][0] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 8)
{
if (table[2][1] == 0)
{
table[2][1] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 9)
{
if (table[2][2] == 0)
{
table[2][2] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
}
int TicTacToe::chkWin()
{
for (int i = 0; i < SIZE; i++)
{
if (table[i][0] == table[i][1] && table[i][0] == table[i][2])
{
if (table[i][0] == 1)
{
results[0] += 1;
winner = 1;
}
else if (table[i][0] == 2)
{
results[2] += 1;
winner = -1;
}
}
else if (table[0][i] == table[1][i] && table[0][i] == table[2][i])
{
if (table[0][i] == 1)
{
results[0] += 1;
winner = 1;
}
else if (table[0][i] == 2)
{
results[2] += 1;
winner = -1;
}
}
}
if ((table[0][0] == table[1][1] && table[0][0] == table[2][2]) || (table[0][2] == table[1][1] && table[0][2] == table[2][0]))
{
if (table[1][1] == 1)
{
results[0] += 1;
winner = 1;
}
else if (table[1][1] == 2)
{
results[2] += 1;
winner = -1;
}
}
else
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if(table[i][j] == 0)
{
winner = 2;
}
}
}
results[1] += 1;;
return winner;
}
}
string TicTacToe::getResults(string name1, string name2)
{
return ( name1 + " : " + to_string(results[0]) + "\n"
+ "Draws : " + to_string(results[1]) + "\n"
+ name2 + " : " + to_string(results[2]) + "\n");
}
Compareing functions with integers doesn't make sense. You have to use () operator to call functions like this:
if (game.chkWin() == 1)
instead of
if (game.chkWin == 1)
Poor:
game.setMove(choice_num, 1);
if (game.chkWin == 1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == -1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == 0)
{
cout <<"The Game is a Draw! ";
}
Better:
game.setMove(choice_num, 1);
switch (game.chkWin()) {
case 1:
cout << name1 << " has won this Game!";
break;
case -1:
cout << name1 << " has won this Game!";
break;
case 0:
cout <<"The Game is a Draw! ";
break;
}
The basic problem is using "==" with function game.chkWin, instead of with the result of function game.chkWin().
But in cases like this (pun intended) a "switch()" block is probably more readable and better style than multiple "if/else" statements.
'Hope that helps...

"Return" not working, cannot "exit" a function [closed]

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 8 years ago.
Improve this question
I have some functions that need to be called multiple times, as such
int i;
i = 10;
while (i > 0)
{
selectletter(wordArray);
computerTurn(wordArray);
printGrid(grid);
i--;
}
The function selectletter works fine, and near the end of that function, it calls another function, "claimword". Claimword runs entirely fine, but at the end of the function, the program crashes when it runs out of context, as opposed to it just moving on to computerTurn as it should as shown above. I looked up on SO how to "exit" a function, and everyone said that "return;" would work fine, even in a void function. However, when I try using return, nothing at all happens, except for anything after the return statement is ignored. Can anyone tell me why the return statement doesn't work?
void claimword(Tile grid[7][6], char letter, string wordArray[100])
{
cout << "Would you like to claim a word? (Y/N)" << endl;
char chooseinput;
cin >> chooseinput;
if ((chooseinput == 'y') || (chooseinput == 'Y'))
{
printGrid(grid);
cout << "Please enter the word you would like to claim." << endl;
string input;
cin >> input;
int inthegrid = 0;
int errormessage = 0;
compchecker(grid, input, inthegrid);
int length;
if (inthegrid = 1)
{
for(int i = 0; i < 100; ++i)
{
if (input == wordArray[i])
{
if (input.find(letter) != std::string::npos)
{
string strl;
strl = wordArray[i];
length = strl.length();
cout << "You have claimed the word " << strl << endl;
wordArray[i] = "/";
}
else
{
errormessage = 1;
}
}
else
{
///cout << "Sorry, that word is not in the dictionary." << endl;
errormessage = 2;
}
}
if (errormessage = 1)
{
cout << "Sorry you cannot claim that word." << endl;
}
if (errormessage = 2)
{
cout << "Sorry, that word is not in the dictionary." << endl;
}
if (length == 3)
{
human.humanpoints = human.humanpoints + 1;
wordsthisturn = wordsthisturn + 1;
cout << "You have earned one point!" << endl;
}
if (length == 4)
{
human.humanpoints = human.humanpoints + 2;
wordsthisturn = wordsthisturn + 2;
cout << "You have earned two points!" << endl;
}
if (length == 5)
{
human.humanpoints = human.humanpoints + 4;
wordsthisturn = wordsthisturn + 4;
cout << "You have earned four points!" << endl;
}
if (length == 6)
{
human.humanpoints = human.humanpoints + 8;
wordsthisturn = wordsthisturn + 8;
cout << "You have earned eight points!" << endl;
}
if (length == 7)
{
human.humanpoints = human.humanpoints + 16;
wordsthisturn = wordsthisturn + 16;
cout << "You have earned sixteen points!" << endl;
}
else
{
cout << "Your word was too small to claim any points." << endl;
}
}
}
else
{
cout << "End of Player Turn." << endl;
//return;
}
cout <<"Test1";
return;
cout <<"Test2";
}
Regardless of the input I give it (y/n and such), "Test1" displays, but "Test2" doesn't. My theory is that the program doesn't return all the way, or I'm just simply not using it right.
EDIT:
With an edited statement in the main function,
selectletter(wordArray);
cout << "test11";
computerTurn(wordArray);
What should happen is that the selectletter function should be called. The selectletter function, at the end of it, calls another function, claimWord. claimWord is posted above. At the end of the function, it should end. There should be nothing left for it to do, and after all those if/elses regarding points, and even if no points are scored, or anything in the function happens, the function should end. The program should then display "test11", but it does not.
EDIT2:
void selectletter(string wordArray[100])
{
cout << endl;
cout << "REMAINING LETTERS:" << endl;
cout << human.humanletters << endl;
cout << "Select a letter.";
int length;
length = human.humanletters.size();
char input;
cin >> input;
int column;
int row = 7;
int cinput;
//mght have to change since 0 is the first val
cout << "What column would you like to drop that in? (1-7)";
cin >> cinput;
column = cinput - 1;
//cout << "Test1";
while (row > 0)
{
if (grid[row-1][column].active == true)
{
row--;
//cout << "Test3";
}
else
for(int i = 0; i < length; i++)
{
if(human.humanletters[i] == input)
{
//cout << "Test5";
human.humanletters.erase(std::remove(human.humanletters.begin(), human.humanletters.end(), input), human.humanletters.end());
grid[row-1][column].letter = input;
grid[row-1][column].active = true;
cout << endl;
//cout << "Test6";
claimword(grid, input, wordArray);
//this removes ALL instances of the letter, however
}
break;
//need to add something for if the letter is not in the string
//}
//row = 9999;
}
}
}
Regardless of the input I give it (y/n and such), "Test1" displays, but "Test2" doesn't.
That is what it is supposed to do. You called return after displaying Test1 and before displaying Test2, so the latter was skipped. return is an immediate return to the function that called the current function.
Your while loop has the condition while (row > 0), and you only decrement row when (grid[row-1][column].active == true). If that ever evaluates to false, you won't decrement row and your program runs forever.
Perhaps your break; was meant to break out of the while loop, but all it will do is break out of the for loop. A break statement breaks out of the nearest enclosing loop/switch block.

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.