Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
Improve this question
My loop is skipping the nested 3rd else if. What should I do so it does not skip it?
#include <iostream>
int main()
{
int loop, i;
loop = 0;
char choice, selection;
std::cout << "Welcome" << std::endl;
while (loop == 0)
{
std::cout << "Please a choice" << std::endl;
std::cout << "a. Run" << std::endl;
std::cin >> selection;
if (selection == 'a')
{
for (i = 1; i < 5; i++)
{
std::cout << "run" << std::endl;
std::cout << "do you want to continue running? (y/n)";
std::cin >> choice;
if (i < 5 && choice == 'y')
{
continue;
}
else if (i < 5 && choice == 'n')
{
break;
}
else if ( i > 5 && choice == 'y')
{
std::cout << "Limit Reached";
}
}
}
I want it to print "limit reached" when i > 5, but somehow the loop skips it. What am I doing wrong?
Previous StackOverflow questions did not help much. I tried their solutions, but they did not solve my issue.
Edit:
For example: Nesting if statements inside a While loop? I have looked if I have initialized any of my int which might be messing my loop.
Looks like my else if didn't work because the condition I gave it would never be true. I feel stupid. But thanks everyone for your time. I really appreciate it.
Your loop runs only while i is in the range 1..4 inclusive, so i < 5 will always be true and i > 5 will never be true.
You should check the value of i after the loop exits. You should also check the user's input to make sure it matches your expectations.
Try something more like this:
#include <iostream>
#include <cctype>
bool shouldContinue(const char *prompt)
{
char choice;
do
{
std::cout << prompt << " (y/n)";
if (!(std::cin >> choice)) throw ...;
if (choice == 'y' || choice == 'Y' || choice == 'n' || choice == 'N') break;
std::cout << "Invalid choice" << endl;
}
while (true);
return (choice == 'y' || choice == 'Y');
}
int main()
{
bool loop = true;
int i;
char selection;
std::cout << "Welcome" << std::endl;
while (loop)
{
std::cout << "Please a choice" << std::endl;
std::cout << "a. Run" << std::endl;
std::cin >> selection;
if (selection == 'a')
{
for (i = 1; i < 5; ++i)
{
std::cout << "run" << std::endl;
if (!shouldContinue("do you want to continue running?"))
break;
}
if (i == 5)
std::cout << "Limit Reached";
}
...
}
return 0;
}
Related
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 7 months ago.
Improve this question
Sorry if my code is garbage, I just started programming, and I'm sure there are quite a few things I'm doing wrong. Please also let me know on how I can improve this. I'm trying to create a program that checks the password a user enters. Right now I keep getting an invalid types error. Would appreciate any help:)
#include <iostream>
#include <vector>
#include <cstring>
#define N 20
// Program that checks for a secure password so far
class Password
{
public:
char UserPassword[N];
int MenuChoice;
int Length;
int LowerCaseAmount = 0;
int UpperCaseAmount = 0;
int DigitAmount = 0;
int SpecialCharAmount = 0;
void Menu()
{
std::cout << "1. Check my current password \n"
<< "2. Generate me a secure password \n"
<< std::endl;
std::cin >> MenuChoice;
if (MenuChoice == 1)
{
//
}
else if (MenuChoice == 2)
{
//
}
else
{
std::cout << "INVALID OPTION! ";
}
}
void CheckPassword()
{
std::cout << "Enter your current password : \n";
std::cin.ignore();
std::cin >> UserPassword;
if (strlen(UserPassword) >= 10)
{
Length = strlen(UserPassword);
for (int i=0; i<Length; i++)
{
if (Length[i] == 'a' && Length[i] == 'z') ++LowerCaseAmount;
if (Length[i] == 'A' && Length[i] == 'Z') ++UpperCaseAmount;
if (Length[i] == '0' && Length[i] == '9') ++DigitAmount;
if (Length[i] == '!' && Length[i] == '*') ++SpecialCharAmount;
}
if (LowerCaseAmount > 0 && UpperCaseAmount > 0 && DigitAmount > 0 && SpecialCharAmount > 0)
{
std::cout << "Secure! ";
}
else if (LowerCaseAmount == 0)
{
std::cout << "Try adding some lower case letters! ";
}
else if (UpperCaseAmount == 0)
{
std::cout << "Try adding some upper case letters! ";
}
else if (DigitAmount == 0)
{
std::cout << "Try adding some numbers! ";
}
else if (SpecialCharAmount == 0)
{
std::cout << "Try adding some special characters! ForEX : #, $, % ";
}
}
else
{
std::cout << "Password should be ten digits or loner! "
<< std::endl;
}
}
};
int main()
{
return 0;
}
int Length;
You declared an int class member called Length.
if (Length[i] == 'a' && Length[i] == 'z')
This is using Length as if it was an array (or some container with an [] overload). Length is not an array. Length is just a plain, boring, lonely int, see above. This is the reason for your compilation error.
Looking at the overall code, it seems that you should be looking at userPassword here, which is your array (or array-like) object.
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 2 years ago.
I'm new to programming and trying a program that You need to guess the name of a video game character, there are only 3 guesses if you ran out of guesses you will lose. I used a do-while loop here so I can do it again and again... The problem here is that every time The loop starts again It displays the prompt 2 times even though It's supposed to be 1 time prompt per guess but it displays 2 prompt. Can you please help me maybe I'm doing the algorithm wrong, Thanks!
#include <iostream>
using namespace std;
int main()
{
char rerun_option;
do {
string secretWord = "Arthur Morgan";
string guess;
int guessCount = 0;
int guessLimit = 3;
bool outofGuesses = false;
while (secretWord != guess && !outofGuesses) {
if (guessCount < guessLimit) {
cout << "Enter video game character name guess: ";
getline(cin, guess);
guessCount++;
}
else {
outofGuesses = true;
}
}
if (outofGuesses) {
cout << "You Lose!" << endl;
outofGuesses = false;
}
else {
cout << "You Win!" << endl;
}
cout << "Try Again?(Y/N) ";
cin >> rerun_option;
} while (rerun_option == 'Y' || rerun_option == 'y');
return 0;
}
EDIT: stackoverflow.com/a/21567292/4645334 is a good example of your problem, explains why you are experiencing it, and explains how you can solve it. I have provided a working example of your code below, as well as a link to more information on the use and description of cin.ignore().
#include <iostream>
using namespace std;
int main()
{
char rerun_option;
do {
string secretWord = "Arthur Morgan";
string guess;
int guessCount = 0;
int guessLimit = 3;
bool outofGuesses = false;
while (secretWord != guess && !outofGuesses) {
if (guessCount < guessLimit) {
cout << "Enter video game character name guess: ";
cin.ignore(); // <-- ADD THIS LINE RIGHT HERE
getline(cin, guess);
guessCount++;
}
else {
outofGuesses = true;
}
}
if (outofGuesses) {
cout << "You Lose!" << endl;
outofGuesses = false;
}
else {
cout << "You Win!" << endl;
}
cout << "Try Again?(Y/N) ";
cin >> rerun_option;
} while (rerun_option == 'Y' || rerun_option == 'y');
return 0;
}
https://www.tutorialspoint.com/what-is-the-use-of-cin-ignore-in-cplusplus
I want the user to choose between playing the game again or ending the program, however when prompted, if they press 'y' the same thing gets repeated over and over instead of the whole program from the very beginning. I've tried while loops, do/while loops, if statements, rearranging the code, but nothing has worked. Any advice?
#include <iostream>
#include <string>
using namespace std;
int main(){
string animal = "fish";
string guess;
char choose = 'Y' ;
int count = 0;//keeps a running total of how many times the user
has guessed an answer.
int limit = 5;//allows user to guess only 5 times, otherwise
they loose the game.
bool out_of_guesses = false;//to check whether the user has run
out of guesses.
cout << "I am thinking of an animal.\n" << endl;
do{
while(animal != guess && !out_of_guesses){//Nested while
loop inside main loop to keep track of how many tries the user has
attempted and to validate their answers.
if(count < limit){
cout << "Can you guess what animal I am thinking of?: ";
getline(cin, guess);
count++;
if(animal != guess){
cout << "\nHmm, nope. That's not the animal I'm
thinking of." << endl;
if(count > 2 && count <5){
cout << "I'll give you a hint. It lives in
water." << endl;
}
}
}
else{
out_of_guesses = true;
}
}//End nested while loop
if(out_of_guesses){
cout << "\nI'm sorry, but you are out of guesses." <<
endl;
}
else{
cout << "\n*** Good job! You guessed the correct animal!
***" << endl;
cout << "\t\t><)))º> ❤ <º)))><\t\t" << endl;
}
//The do-while loop is there to ask the user if they wish to
play the game again.
cout << "Would you like to try again?(y/n): ";
cin >> choose;
if(choose == 'N' || choose == 'n')
break;
}while(choose == 'Y' || choose == 'y');
return 0;
}
The bool out_of_guesses = false; must be in-between while(true) and while(animal != guess && !out_of_guesses), and not outside the first while loop. Because our while loop condition is always false, and then it does enter it.
You should also reset your guess variable in-between those 2 loops, else same thing could happen (false while loop) in case of the answer is found.
Here the code with some refactoring/review, which I used the guess as upper case to handle any typography of the answer. I also removed the out of guess variable to use the count and limit one instead.
#include <iostream>
#include <string>
#include <cctype>
int main()
{
const std::string animal = "FISH";
const int limit = 5;
do
{
std::cout << "I am thinking of an animal.\n";
int count = 0;
std::string guess;
while(animal.compare(std::toupper(guess)) != 0 && count < limit)
{
std::cout << "Can you guess what animal I am thinking of?: \n";
std::cin >> guess;
count++;
if(animal.compare(std::toupper(guess)) != 0)
{
std::cout << "\nHmm, nope. That's not the animal I'm thinking of.\n";
if(count > 2)
{
std::cout << "I'll give you a hint. It lives in water.\n";
}
}
}
}//End nested while loop
if(count >= limit)
{
std::cout << "\nI'm sorry, but you are out of guesses.\n";
}
else
{
std::cout << "\n*** Good job! You guessed the correct animal! ***\n";
std::cout << "\t\t><)))º> ❤ <º)))><\t\t\n";
}
char choose = 'Y' ;
std::cout << "Would you like to try again?(y/n): ";
std::cin >> choose;
if(std::toupper(choose) == 'N') break;
} while(true);
return 0;
}
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.
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.