why am i getting so many numbers from my array c++ - c++

I'm still working on this project and I have most of my problems fixed.
The problem shows itself while using selection B, but lies in option A and sending the array to the .txt file. There are a lot of extra numbers being added to the .txt file. When I cout, it displays the numbers in the array like it should, but in the text file it looks like this
Anthony201910181114-8589934604445358131768008182078541176802418196927161130726102120444535893
everything before the - is correct, but all of these numbers after need to go.
Why is this happening and how can I fix this?
Thank you.
int main()
{
int Stats[6];
char Selection;
string Character1;
int i;
char keep;
do
{
cout << "Hello, welcome to my character generator. Please select an option" << endl;// Menu Options
cout << "A: Create Character Name and generate stats" << endl;
cout << "B: Display Name and Stats" << endl;
cout << "C: Quit" << endl;
cin >> Selection; // Menu Selection
cout << endl;
if ( (Selection == 'a') || (Selection == 'A') )// if user selects a, this happens
{
cout << "Welcome, Before you can start your adventures you must name your character." << endl;
do
{
cout << "Please enter your a name." << endl;// prompts user to enter a name for their Caracter
cin >> Character1;
cout << "Thank you now lets generate your stats." << endl;
for (i=0; i<6;i++)// I Want this to run the function GenerateScore() 6 times and input each result into the next element of Stats[6]
{
Stats[i]=GenerateScore();
}
for(i=0;i<6;i++)// displays your scores to the player.
{
cout << Stats[i]<< endl;
}
cout << "would you like to keep this name and these Stats?"<< endl;
cout << "Y/N" << endl;
cin >> keep;
break;
}
while ( (keep=='n') || (keep=='N') );
ofstream savecharinfo("charactersave.txt");// saves the Name and the filled array Stats[6] to the charactersave.txt file
if(savecharinfo.is_open())
{
savecharinfo << Character1;
for(int i = 0; i<6; i++)
{
savecharinfo << Stats[i];
}
}
else cout << "File could not be opened." << endl;
}
else if ( (Selection =='b') || (Selection == 'B') )
{
cout << " Welcome back, here are is your character." << endl;
ifstream displaycharacter("charactersave.txt");
if(displaycharacter.is_open())
{
while ( getline (displaycharacter,Character1) )
{
cout << Character1 << endl;
}
displaycharacter.close();
}
else cout << "File could not be opened";
}
else
break;
}
while ( (Selection != 'c') || (Selection == 'C') ); // ends the program is c or C is entered.
return 0;
}
int GenerateScore()
{
int roll1 = rand()%6+2;
int roll2 = rand()%6+2;
int roll3 = rand()%6+2;
int sum;
sum=roll1+roll2+roll3;
return sum;
}

Like was mentioned in the comments:
while ( (keep='n') || ('N') );
should (at least) be changed to
while ( (keep == 'n') || (keep == 'N') );
Also, this loop:
for(int i = 0; Stats[i]; i++)
Will only terminate when Stats[i] evaluates to false, which will only happen when Stats[i] == 0. This loop is causing the extra chars in the file: the code keeps accessing out of bounds array elements until randomly the out of bounds element == 0. You probably want for(int i = 0; i < 6; i++)

Related

C++ Possible scope issue in the quit() function

Tried declaring and initializing selection to have another value other than 'Q' and returning that value so that do while loop would keep running. I can't seem to change the value of the selection variable from inside of a function named quit(). the selection variable is defined within the get_selection() function. I am still very new to coding and C++ can somebody help me with this? I don't know how to change the value of selection to keep the do while loop running once someone enters 'q' or 'Q' to quit the loop. The source code is below. This is my first stack overflow question. Please give constructive feedback if i have asked this question in a bad way so that I learn from it and do better next time. Thank you so much for your time and hope you have a blessed day.
#include <iostream>
#include <vector>
using namespace std;
// Function Prototypes
void display_menu();
char get_selection();
void print_numbers(const vector<int> &list);
void add_number(vector<int> &list);
void remove_number(vector<int> &list);
void display_mean(const vector<int> &list);
void smallest_number(const vector<int> &list);
void largest_number(const vector<int> &list);
char quit();
void handle_unknown();
// End of Function Prototypes
void display_menu() {
cout << "-------------------------------------------\n";
cout << "Please select one of the following choices:|\n ";
cout << "P - Print Numbers |\n ";
cout << "A - Add a Number |\n ";
cout << "R - Remove a Number |\n";
cout << " M - Display Mean of the Numbers |\n ";
cout << "S - Display the Smallest Number |\n ";
cout << "L - Display the Largest Number |\n ";
cout << "Q - Quit |\n ";
cout << "-------------------------------------------\n";
cout << "\nEnter Selection Here: ";
}
char get_selection() {
char selection {};
cin >> selection;
return toupper(selection);
}
void print_numbers(const vector<int> &list) {
// if the User selects P it will display the list within brackets
cout << "\n============================================\n";
cout << "\n[ ";
for ( auto index : list) {
cout<< index << " ";
}
cout << "]";
cout << "\n\n============================================\n\n";
}
void add_number(vector<int> &list) {
// if the user selects A it will Add a Number to the list
int number {};
cout << "\n==========================================================\n\n";
cout << "- Please enter a number to be ADDED to the list: ";
cin >> number;
list.push_back(number);
cout << "- The number " << number << " was ADDED to the list\n\n";
cout << "==========================================================\n\n";
}
void remove_number(vector<int> &list) {
// if the user selects R it will REMOVE a Number from the list
char choice {};
cout << "\n- If you select Yes the last number you added to the list will be REMOVED from the list(Y/N): ";
cin >> choice;
if ( (choice == 'Y' || choice == 'y') && list.size() == 0) {
cout << "- Sorry, but there is currently nothing in the list to remove.\n\n";
cout << "==========================================================================================================\n\n";
}
else if (choice == 'Y' || choice == 'y'){
list.pop_back();
cout<< "- The last number you entered was removed from the list\n\n";
cout << "==========================================================================================================\n\n";
}
else if (choice == 'N' || choice == 'n') {
cout << "- The number survived the purge!!!\n\n";
cout << "==========================================================================================================\n\n";
}
else {
cout << "- You did not enter a valid response, no action was taken\n\n";
cout << "==========================================================================================================\n\n";
}
}
void display_mean(const vector<int> &list) {
// if the user selects M it will display the mean of the numbers
cout << "\n===============================================================\n\n";
int sum {}; //all the integers in the list added together
double mean {}; // the sum / list.size()
for ( auto integer : list) {
sum = sum + integer;
}
mean = static_cast<double>(sum) / list.size();
cout << "- The Sum of all the numbers in the list is: " << sum << endl;
cout << "- The Mean of all the numbers in the list is: " << mean << endl;
cout << "\n===============================================================\n";
}
void smallest_number(const vector<int> &list) {
// Displays the smallest number
cout << "\n=========================================================\n\n";
int min = list.at(0);
for ( auto nums : list ) {
if ( nums < min) {
min = nums;
}
}
cout << "- The Min in the list is: " << min << endl;
cout << "\n=========================================================\n\n";
}
void largest_number(const vector<int> &list) {
// Displays the largest number
cout << "\n=========================================================\n\n";
int max = list.at(0);
for ( auto nums : list ) {
if ( nums > max) {
max = nums;
}
}
cout << "- The Max in the list is: " << max << endl;
cout << "\n=========================================================\n\n";
}
char quit() {
// Are you sure you want to quit prompt
char quit_prompt {};
cout << "\n==============================================\n\n";
cout << "Are you sure you want to quit (Y/N)? ";
cin >> quit_prompt;
if ( quit_prompt == 'Y' || quit_prompt == 'y') {
cout << "Have a blessed day!!!" << endl;
cout << "\n==============================================\n\n";
return 'a';
}
else if ( quit_prompt == 'N' || quit_prompt == 'n') {
cout << "Choose a option\n";
cout << "\n==============================================\n\n";
display_menu();
return get_selection();
}
else if ( quit_prompt == 'Q' || quit_prompt == 'q') {
cout << "Have a blessed day!!!\n";
cout << "\n==============================================\n\n";
return 'a';
}
else {
cout << "You entered a invalid response, no action was taken\n";
cout << "\n==============================================\n\n";
display_menu();
return get_selection();
}
}
void handle_unknown() {
cout << "Unknown selection - try again" << endl;
}
int main() {
vector<int> list {1,2,3}; //have to create the list outside of the loop otherwise the loop will
reset the list every single time the loop resets (lesson learned)
// user input a character that will get saved to this selection variable
char selection {};
// run this loop unless the user inputs 'Q' or 'q'
do {
// tells the user to enter a valid choice if they don't
display_menu();
selection = get_selection();
switch (selection) {
case 'P':
print_numbers(list);
break;
case 'A':
add_number(list);
break;
case 'R':
remove_number(list);
break;
case 'M':
display_mean(list);
break;
case 'L':
largest_number(list);
break;
case 'S':
smallest_number(list);
break;
case 'Q':
quit();
break;
default:
handle_unknown();
}
} while ( selection != 'Q' ); // using the && logical statement because of the != comparison.
return 0;
}
You return a value from the quit function, but you don't save it or act upon it in the main function.
You should probably not return a value from the quit function, and neither should it display the menu or get the selection, as it's done in the main function. Instead I would suggest something like
void quit() {
// Are you sure you want to quit prompt
char quit_prompt {};
cout << "\n==============================================\n\n";
cout << "Are you sure you want to quit (Y/N)? ";
cin >> quit_prompt;
if ( quit_prompt == 'Y' || quit_prompt == 'y' ||
quit_prompt == 'Q' || quit_prompt == 'q') {
cout << "Have a blessed day!!!" << endl;
cout << "\n==============================================\n\n";
exit(0); // Exit the program
}
else if ( quit_prompt == 'N' || quit_prompt == 'n') {
// Do nothing
}
else {
cout << "You entered a invalid response, no action was taken\n";
cout << "\n==============================================\n\n";
}
}

How to successfully restart loop and accept new responses?

I am attempting to create a program that can print ascii art letters when given J, E, or C and the size (7 or greater and an odd number). I have been able to successfully run the program until I added a Y/N response prompt. I would like to ask the user if they would like to continue, if yes, then I would like to restart the loop. However, I'm trying to write the code to meet the conditions of if they enter 'e' then 'e' ascii art prints, if they enter 'c' then ascii art prints, etc. However, I cannot figure out how to restart the loop and accept new information.
Also, my current predicament is that the do loop is not meeting with my last while loop for a 'No' response. I'm new to C++ and would appreciate any help that can be provided. Thank you!
#include <iostream>
using namespace std;
int main() {
int s;
char l;
char choice;
cout << "Welcome to the letter printer." << endl;
do {
cout << "Enter the size: " << endl;
cin >> s;
while (s < 7 || s % 2 == 0 || s < 0) {
cout << "Invalid size. Enter the size again: " << endl;
cin >> s;
}
cout << "Enter the letter: " << endl;
cin >> l;
while (l != 'c') {
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> l;
}
if (l == 'c') {
int size = s;
for (int row = 0; row < size; row++) {
cout << "*";
for (int col = 0; col < size - 1; col++) {
if (row == size - 1)
cout << "*";
else
cout << " ";
if (row == 0)
cout << "*";
else
cout << " ";
}
cout << endl;
}
}
} while (choice == 'N');
return 0;
}
You're using choice without reading into it. Additionally, the check while (choice == 'N') doesn't make sense, you want to continue while the choice is no?
Here's the gist of it with the irrelevant parts cut for brevity.
#include <iostream>
int main() {
char choice{};
std::cout << "Welcome to the letter printer.\n";
do {
int s{};
std::cout << "Enter the size: " << std::flush;
std::cin >> s;
// ... check for size ...
char l{};
std::cout << "Enter the letter: " << std::flush;
std::cin >> l;
// ... check for letter ... draw letter ...
std::cout << "would you like to continue? (Y/N): " << std::flush;
std::cin >> choice;
} while (choice == 'Y');
}
For future reference, most of the code in your question isn't directly relevant to the problem, the restrictions on what letters to enter, the size restriction, and the drawing of the letter could all be left out when making your example. Doing this tends to reveal the problem.
I have fixed your code and in the meantime I want to make a few remarks for the future.
Before posting to StackOverflow asking for debugging, debug it yourself. I understand sometimes you may have a sore head from looking at the same code for a long time but not everyone likes debugging code here.
Have some decency and post code that is at the least functioning to some degree. It is a complete pain trying to find curly braces, commas, etc. that you should have found yourself.
Next time isolate your problem in your code before posting it here.
Regarding your code, you were thinking in the right direction.
In while(choice == 'N') [As pointed out by Raindrop7 & Ryan Haining], your char choice was undeclared. Simple fix is to declare / use the variable like cin >> choice in the example below.
Name your variables with sense, it s hard to keep track of a variable when it is being used everywhere e.g. [char s, int l].
Encapsulate code if it is being reused a lot e.g. [void PrintLetter(char, int)]
Side Note: Next time you encounter a bug. Put some kind of animal toy beside you and speak your problem out to it. Usually you'll answer your own question.
#include "stdafx.h"
#include <iostream>
using namespace std;
void PrintLetter(char letter, int size)
{
switch (letter)
{
case 'c':
for (int row = 0; row < size; row++)
{
cout << "*";
for (int col = 0; col < size - 1; col++)
{
if (row == size - 1)
{
cout << "*";
}
else
{
cout << " ";
}
if (row == 0)
{
cout << "*";
}
else
{
cout << " ";
}
cout << endl;
}
}
break;
case 'f':
break;
case 'l':
break;
}
}
int main() {
int size;
char letter;
char choice;
cout << "Welcome to the letter printer." << endl;
do {
cout << "Enter the size: " << endl;
cin >> size;
while (size < 7 || size % 2 == 0 || size < 0) {
cout << "Invalid size. Enter the size again: " << endl;
cin >> size;
}
cout << "Enter the letter: " << endl;
cin >> letter;
while (letter != 'c') {
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> letter;
}
PrintLetter(letter, size); // Print Letter In Here, Function At The Top
cout << "Would you like to continue? [Y,N]" << endl;
cin >> choice;
}while (choice == 'Y' || choice == 'y'); // End Do While
return 0;
} // End Main

How to inverse string without library functions - C++

I'm having trouble with understanding how to output the inverse of the string then store the inverse value and apply it to a string variable to print the string later on. Some errors I receive depending on the structure of the program include : random characters being printed, just the string input being printed, the programming crashing... The program must be able to process this menu:
At one point I had the inverse working, but when I would add for example if(choice == '2') and create the reverse function it would start acting up again.
This is what I have for now :
int main()
{
string userString = "";
int i = 0;
char choice;
char invChar = char(userString[i]);
userString = invChar;
cout << "Please enter a word, a sentence, or a string of numbers." << endl;
getline(cin, userString);
do
{
cout << "\nUSE THIS MENU TO MAINPULATE YOUR STRING\n"
<< "----------------------------------------" << endl;
cout << "1) Inverse String\n"
<< "2) Reverse String\n"
<< "3) To Uppercase\n"
<< "4) Count Number Words\n"
<< "5) Count Consonants\n"
<< "6) Enter a Different String\n"
<< "7) Print the String\n"
<< "Q) Quit" << endl;
cin >> choice;
cin.ignore();
if (choice == '1')
{
for (int i = 0; i <= userString.length(); ++i)
{
if (isupper(userString[i]))
{
char(tolower(userString[i])); // if uppercase - converts to lower - if upper keeps value
invChar += userString[i];
}
userString = invChar;
}
cout << userString;
}
} while (choice != 'q' || choice != 'Q');
Thanks in advance for any tips and tricks!
Did you maybe mean to do this:
for (int i = 0; i < userString.length(); ++i)
{
if (isupper(userString[i]))
{
userString[i] = (tolower(userString[i]));
}
else if(islower(userString[i]))
{
userString[i] = (toupper(userString[i]));
}
}
This will actually inverse. What you were doing before doesn't work, and also only converts to uppercase

Saving c++ array of struct to file and issue for adding new elements to it

There are two main problems with my program that I am currently having. The first is I am unable to add more than one account to my program while it is running (I need to close it and re-open before I can add another). The second issue is when I don't add any accounts to my program addresses get saved to the program, this is what the file looks like when I don't add any accounts to the program.
123#John Smith#0#0###-1.07374e+008#-1.07374e+008#
The first part of the file is correct, but the addresses are coming from somewhere else in memory. This is what my code looks like.
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>
#include <sstream>
using namespace std;
struct account
{
string acctNum;
string name;
float cBal;
float sBal;
};
int menu();
char subMenu();
int loadCustomers(account[]);
void saveCusomers(account[], int);
int newCustomer(account[], int);
int deleteCustomer(account[], int);
int findCustomer(account[], int);
void deposit(account[], int);
void withdrawl(account[], int);
void balance(account[], int);
void bankBalance(account[], int);
int main()
{
account acc[20];
int selection;
int numAcc = 0;
int search;
numAcc = loadCustomers(acc);
do
{
selection = menu();
if(selection == 1)
{
newCustomer(acc, numAcc);
}
else if(selection == 2)
{
deleteCustomer(acc, numAcc);
}
else if(selection == 3)
{
search = findCustomer(acc, numAcc);
if (search == -1)
{
cout << "That account doesn't exist." << endl;
system("pause");
system("cls");
}
else
{
cout << right << setw(3) << acc[search].acctNum << "" << left << setw(15) << acc[search].name << acc[search].cBal << acc[search].sBal << endl;
system("pause");
system("cls");
}
}
else if(selection == 4)
{
deposit(acc, numAcc);
}
else if(selection == 5)
{
withdrawl(acc, numAcc);
}
else if(selection == 6)
{
balance(acc, numAcc);
}
else if(selection == 7)
{
bankBalance(acc, numAcc);
}
else if(selection == 8)
{
break;
}
} while (selection != 8);
saveCusomers(acc, numAcc);
return 0;
}
int menu()
{
int select;
cout << "Main Menu" << endl;
cout << "=============" << endl;
cout << "1. New Account" << endl;
cout << "2. Delete Account" << endl;
cout << "3. Find Customer" << endl;
cout << "4. Deposit" << endl;
cout << "5. Withdrawl" << endl;
cout << "6. Balance" << endl;
cout << "7. Bank Balance" << endl;
cout << "8. Exit" << endl;
cout << "=============" << endl;
cout << "Enter choice: ";
cin >> select;
while (select < 1 || select > 8)
{
cout << "Invalid input, select a number between 1 and 8: ";
cin >> select;
}
system("cls");
return select;
}
char subMenu()
{
char choice;
cout << "Which account? <C>hecking or <S>aving: ";
cin >> choice;
while(choice != 'C' && choice != 'c' && choice != 'S' && choice != 's')
{
cout << "Invalid choice, choose either checking or saving: ";
cin >> choice;
}
return choice;
}
int loadCustomers(account acc[])
{
ifstream inFile;
int numCustomers = 0, i = 0;
string ctemp, stemp;
inFile.open("customer.dat");
if (!inFile)
{
cout << "No customer file found." << endl;
}
else
{
cout << "Customer file found..." << endl << endl;
while (getline(inFile, acc[i].acctNum, '#'))
{
getline(inFile, acc[i].name, '#');
getline(inFile, ctemp, '#');
getline(inFile, stemp, '#');
istringstream(ctemp) >> acc[i].cBal;
istringstream(stemp) >> acc[i].sBal;
i++;
numCustomers++;
}
cout << "Number of customers found in file: " << numCustomers << endl;
}
system("pause");
system("cls");
inFile.close();
return numCustomers;
}
void saveCusomers(account acc[], int numCustomers)
{
ofstream outFile;
outFile.open("customer.dat");
for (int i = 0; i < numCustomers; i++)
{
outFile << acc[i].acctNum;
outFile << '#';
outFile << acc[i].name;
outFile << '#';
outFile << acc[i].cBal;
outFile << '#';
outFile << acc[i].sBal;
outFile << '#';
}
outFile << acc[numCustomers].acctNum;
outFile << '#';
outFile << acc[numCustomers].name;
outFile << '#';
outFile << acc[numCustomers].cBal;
outFile << '#';
outFile << acc[numCustomers].sBal;
outFile << '#';
cout << numCustomers + 1 << " accounts saved into the file." << endl;
outFile.close();
}
int newCustomer(account acc[], int numCustomers)
{
cout << "New Customer" << endl;
cout << "============" << endl;
cout << "Enter account number: ";
cin >> acc[numCustomers].acctNum;
cout << "Enter name: ";
cin.ignore();
getline(cin, acc[numCustomers].name);
acc[numCustomers].cBal = 0;
acc[numCustomers].sBal = 0;
numCustomers++;
return numCustomers;
}
int deleteCustomer(account[], int)
{
return 0;
}
int findCustomer(account acc[], int numCustomers)
{
string target;
cout << "Enter the account number you are looking for: ";
cin >> target;
for (int i = 0; i < numCustomers; i++)
{
if (acc[i].acctNum == target)
{
return i;
}
}
return -1;
}
How can I change this to make it so I can add more than one account when the program is running, and how can I make it so the program won't save an address to my file when nothing is added? I would also like to know why those addresses are being saved like that.
In main() you loadCustomers() in acc[] and you keep a record of the number of customers in local variable numAcc. At the end of main() you saveCustomers() the numAcc in acc[].
1. Your saving function is wrong:
in your loop for (int i = 0; i < numCustomers; i++) { ...}, you first write each customer from 0 to numAcc-1. This is correct.
But afterwards you write again an additional account, with the offset of numAcc. So you're writng one more account than you have. And the values of this account are not initialized, which explains the weird numbers you see.
You do this even if no account was added. And you know that you are doing it, because you've written cout << numCustomers + 1 << " accounts saved into the file."
Correction: just save the accounts you have, in the loop.
2.Your adding function is correct but you don't use it as you've planned:
When you add a customer with newCustomer() your function increments its local variable so that it knows that there is one more customer. Your function correctly returns this new number.
Unfortunately, in main() you do nothing with this returned value, so that numAcc remains unchanged.
Correction: Correct the following statement in main():
if (selection == 1)
{
numAcc = newCustomer(acc, numAcc); // update the number of accounts
}
3. Miscellaneous remarks:
You don't check in newCustomers() if your acc[] array is already full. If you add a 21st account, it'll be a segfault !
The same applies to load. You cannot be sure that nobody added a line to the file with a text editor. So there is as well a risk of reading more lines that there is space in your arry.
Nothing happens in deleteCustomer() I suppose you haven't written it yet. Think that this function could change the number of accounts, exactly as newCustomer().
As most banks have more than twenty customers, I assume that it's an exercise for school. I don't know if you're allowed to do so, but I'd highly recommend to replace arrays with vectors.

Input errors in c++ program

when press "1" to start the game a error message comes up first instead of playing the game and then I have to enter "1" 3 times before the game starts and also the quit game option only works when you select "2" first if its not selected first it just comes up as a error message I cant see why it does this can anyone help me please ?
#include "Questions.h"
#include <iostream>
using namespace std;
const int MAXITEMS = 10;
int main ()
{
string question[MAXITEMS] = {"How man cards in a suit",
"How_many_suits_are_there_in_a_standard_pack_of_card",
"How_many_kings_are_in_a_standard_pack_of_cards"};
string answers[MAXITEMS] = {"4", "5", "6"};
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;
};
// when game starts gives option to select question and shows all questions
do
{
if (userInput != 1||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;
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
if(userInput == 1)
{
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 && 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 && tries == 2)
{
cout << "you can no longer answer this question" << endl;
cout << "try another question" << endl;
}
}
while(userInput == 1);
}
}
while(isGameOver == false);
}
// add stuct or class to handle questions,
if (userInput != 1||2) doesn't do what you think. With the proper paretheses inserted, it is
if ((userInput != 1) || 2)
and 2 is nonzero, hence the condition is always true.
You want
if (userInput != 1 && userInput != 2)
The problem lies here:
if (UserInput!=1||2)
In this line, there are two conditions:
UserInput!=1 , 2
Here , whether user input is 1/2, the second condition 2 is always evaluated as true, which runs the if block
So change it to
if (UserInput!=1 && UserInput!=2)