CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2024
    Posts
    1

    if statement being ignored despite conditions being true

    Hi everyone, I've been working on a quiz program for my class and something really strange happened to my program when I opened it today, Whenever I attempt to access the alternate gamemode (endless), the console ignores the if statement that should take you to the game. There are no warnings (besides an srand initialization) that tells me anything, and the program was not behaving this way yesterday, which was the last time I touched this program. I'm seriously lost here. I asked my teacher, and they had no idea. So I come to you, codeguru forum: What the hell is up with my program?? If it helps, I am writing this on xCode version 12.4
    Code:
    int main(int argc, const char * argv[]) {
        
        for (;;){
        
            
            srand(time(NULL)); //randomize seed for rand(),
            int score = 0;//The players score, this is meant to encourage getting answers right consistently, because they lose score if they get a question wrong. This is like their total grade while the 'total' variable is like their mark on a test.
            int streak = 0;//Everytime a player gets an answer correctly, this number goes up by one. If they get a question wrong, it resets to 0.
            int total = 0;//the total amount of questions that the user gets right, think of it as their mark
            int answers[10] = {1,2,3,1,3,2,3,3,1,1};//The Answer key, this tells the computer which input from the user is the correct input to each question
            int uInput;//the actual variable that the user interacts with, it gets compared to the numbers from answers to see if the player answered correctly/
            int menuSel;//menu selection input
            char menuSel2;//alternative menu selection for characters
    
            //A NOTE ON MODDING THE GAMES QUESTIONS: I have tried to make the process as easy as possible if you wish to change the questions/answers. If you want to add/remove questions from the program, make sure to edit:int answers[], string questionBank/answersBank, and change the value of y in the for loop to ensure that everything works, MAKE SURE THAT THE ANSWERS AND QUESTIONS ARE IN THE SAME PLACE IN THEIR RESPECTIVE ARRAYS!!! It will only display them in the order that they are in, unless you are playing endless, where they are randomly selected. I suggest only playing endless mode if you make changes to the code, just for the sake of it being much easier.
        
            string questionBank[10] = {"If you are designing an app and you want your audience to be old ladies, how should you design your app?", "What is ASCII and how do you use it?", "What would the bare minimum requirements be for a calculator program?", "What is another feature you might expect in a basic calculator program?", "When is it appropriate to add an easter egg inside of your program?","You just finished the prototype for your new program, who should you show it to for the best feedback?","You just got a new assignment to create a program for a quiz game about the design process. What should you start working on first?","Who would be the most appropriate candidate to test your C++ program?","What would the ideal audience be for an economy-based game that you developed in C++?","What might be some requirements for a vending machine program?"
                };
            string answersBank[][3] = {{"Very easy to use and with simple controls","An advanced program with technical mechanics, using a large vocabulary ","Use slang terms and acronyms so it will take less time to read"},{"Data storing mechanism that allows you to store data locally","Special characters for decoration and design","A type of loop "},{"Input/Output, loops, and Math","Loops, Math, and Output","Math, and Output"},{"Multiple Step Equations","ASCII art and decoration","Shortcuts"},{"In a personal project with no affiliation to other organizations","In projects you are very proud of","Always"},{"Mr. Dawson","Your classmate who sits right next to you","Mrs. Speechley"},{"The aesthetics of the program","All the questions you want to use for the quiz game","The code itself for the program"},{"A random level 1 student","Mr. Dawson","A nearby level 2"},{"Other C++ fans and programmers","12-year-olds and little kids","Mobile Gamers"},{"Connecting different variables so they can interact with eachother (money, products, etc)","A model of the vending machine","Tracking each sale as a statistic"}};//all of the potential answers to all of the questions
        //initializing input system and variables
    
            cout << "Welcome to The Amazing, Incredible, Super, Awesome, Exciting, Engaging, Fun, Extreme, Unbelievable, Epic, Design Process Game! Select the gamemode you would like to play today.";
            cout << "\n1.Standard\n2.Endless";
            cin >> menuSel;
            if (menuSel==1){
                cout << "Taking you to Standard gameplay..." << endl << endl;
                for (int y=0;y<10; y++){
                    cout << questionBank[y] << endl;
                    for (int x=0;x<3;x++){cout << x+1 << ". " <<answersBank[y][x] << endl;}
                    cin >> uInput;
                    
                cout << "Thank you for playing, your total is:" << total << "/10\n";
           
                if (total==10){
                    cout << "Holy crap, a perfect score! You should try the endless mode for an even bigger challenge!\n";
                    int reset(int);//A relic from when I was trying to have the score and streak/etc reset automatically after you complete the quiz using functions, I scrapped it when I realised that was stupid to create a function to re-declare variables that don't need to be declared differently than they already were, so I created an endless loop that includes the initialization of the variables, since that makes way more sense and is more efficient. Today, it does absolutely nothing so I chose to keep it in the program as a reminder to myself.
                    cout << "Press ENTER to return to menu";
                    system("read");
                }
                else if (total<=9 && total>=5){
                    cout << "Want to try again for a perfect score?";
                    int reset(int);
                    cout << "Press ENTER to return to menu\n";
                    cout << "Score:"<<score<<" Total:"<<total<<" Streak:"<<streak;
                    system("read");
                }
                else if (total<5){
                    int reset(int);
                    cout << "Better luck next time..";
                    cout << "Press ENTER to return to menu";
                    system("read");
                }
                else {
                        cout << "Looks like somebody did something they shouldn't have.. :(\n";
                    int reset(int);
                    cout << "Press ENTER to return to menu\n";
                    cout << "Score:"<<score<<" Total:"<<total<<"Final Streak:"<<streak;
                    system("read");
                    }
            }
                    if (menuSel==2){
                        cout << "WARNING: Endless mode is extremely dangerous and hard, if you get a single question wrong, your run ends. Are you sure you want to continue?" << endl;
                        cout << "Y-Continue\nE-Return to Menu";
                        cin >> menuSel2;
                        if (menuSel2=='E'||menuSel2=='e'){
                            cout << "Returning to menu\n";
                            break;
                        }
                    else if (menuSel2=='Y'||menuSel2=='y'){
                        cout << "Taking you to endless mode..\n";
                        while (bool z=true){
                            int randomGrabr=(rand() % 10);
                            cout << questionBank[randomGrabr] << endl;
                            for (int x=0;x<3;x++){
                                cout << x+1 << ". " <<answersBank[randomGrabr][x] << endl;}
                            cin >> uInput;
                            if (uInput==answers[randomGrabr]){
                                total=total+1;
                                streak=streak+1;
                                if (streak<3){
                                    score=score+250;
                                }
                                if (streak>=10){
                                    score=(score*streak/100)+score;
                                    cout <<"SUPER STREAK! " << streak << endl;
                                }
                                cout << "Correct! So epic! Score:" << score << endl << "Press ENTER to continue" << endl;
                                system("read");
                            }
                            if (uInput!=answers[randomGrabr]){
                                cout << "Incorrect! Game over. You got a total of: " << streak << "answers correct!";
                                
                                }
                            }
                        }
                    }
                }
        
        }
        return 0;
    }

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,903

    Re: if statement being ignored despite conditions being true

    Consider as code refactored to use functions etc. This is OK with VS2022:

    Code:
    #include <iostream>
    #include <cstdlib>
    
    constexpr size_t noQuest { 10 };	// Number of questions
    constexpr int answers[noQuest] { 1, 2, 3, 1, 3, 2, 3, 3, 1, 1 };	// The Answer key, this tells the computer which input from the user is the correct input to each question
    
    // Questions
    const std::string questionBank[noQuest] {
    	"If you are designing an app and you want your audience to be old ladies, how should you design your app?",
    	"What is ASCII and how do you use it?",
    	"What would the bare minimum requirements be for a calculator program?",
    	"What is another feature you might expect in a basic calculator program?",
    	"When is it appropriate to add an easter egg inside of your program?",
    	"You just finished the prototype for your new program, who should you show it to for the best feedback?",
    	"You just got a new assignment to create a program for a quiz game about the design process. What should you start working on first?",
    	"Who would be the most appropriate candidate to test your C++ program?",
    	"What would the ideal audience be for an economy-based game that you developed in C++?",
    	"What might be some requirements for a vending machine program?"
    };
    
    // all of the potential answers to all of the questions
    const std::string answersBank[noQuest][3] { {"Very easy to use and with simple controls",
    	"An advanced program with technical mechanics, using a large vocabulary ",
    	"Use slang terms and acronyms so it will take less time to read"},
    	{"Data storing mechanism that allows you to store data locally",
    	"Special characters for decoration and design",
    	"A type of loop "},
    	{"Input/Output, loops, and Math",
    	"Loops, Math, and Output",
    	"Math, and Output"},
    	{"Multiple Step Equations","ASCII art and decoration",
    	"Shortcuts"},
    	{"In a personal project with no affiliation to other organizations",
    	"In projects you are very proud of","Always"},
    	{"Mr. Dawson","Your classmate who sits right next to you",
    	"Mrs. Speechley"},
    	{"The aesthetics of the program",
    	"All the questions you want to use for the quiz game",
    	"The code itself for the program"},
    	{"A random level 1 student","Mr. Dawson","A nearby level 2"},
    	{"Other C++ fans and programmers",
    	"12-year-olds and little kids",
    	"Mobile Gamers"},
    	{"Connecting different variables so they can interact with eachother (money, products, etc)",
    	"A model of the vending machine",
    	"Tracking each sale as a statistic"} };
    
    void pressEnt() {
    	std::cout << "Press <ENTER> to return to menu\n";
    	std::cin.get(); std::cin.get();
    }
    
    void doscore(int ans, int& score, int& streak, int& total) {
    	int uInput {};
    
    	std::cout << "Your answer: ";
    	std::cin >> uInput;
    
    	if (uInput == answers[ans]) {
    		++total;
    		++streak;
    
    		if (streak < 3)
    			score += 250;
    
    		if (streak >= 10) {
    			score += score * streak / 100;
    			std::cout << "SUPER STREAK! " << streak << '\n';
    		}
    
    		std::cout << "Correct! So epic! Score:" << score << '\n';
    	} else {
    		streak = 0;
    		// score if incorrect??
    		std::cout << "Incorrect!\n";
    	}
    
    	std::cout << "Score:" << score << " Total:" << total << " Streak:" << streak << '\n';
    
    	pressEnt();
    }
    
    void process(int qst, int& score, int&streak, int& total) {
    	std::cout << questionBank[qst] << '\n';
    
    	for (int x {}; x < 3; ++x)
    		std::cout << x + 1 << ". " << answersBank[qst][x] << '\n';
    
    	doscore(qst, score, streak, total);
    }
    
    int main() {
    	srand(time(NULL)); // randomize seed for rand(),
    
    	for (; ;) {
    		// initializing input system and variables
    		int score {};		// The players score, this is meant to encourage getting answers right consistently, because they lose score if they get a question wrong. This is like their total grade while the 'total' variable is like their mark on a test.
    		int streak {};		// Every time a player gets an answer correctly, this number goes up by one. If they get a question wrong, it resets to 0.
    		int total {};		// the total amount of questions that the user gets right, think of it as their mark
    		int menuSel {};		// menu selection input
    
    		std::cout << "Welcome to The Amazing, Incredible, Super, Awesome, Exciting, Engaging, Fun, Extreme, Unbelievable, Epic, Design Process Game! Select the gamemode you would like to play today.";
    		std::cout << "\n1.Standard\n2.Endless\n";
    		std::cout << "Option: ";
    		std::cin >> menuSel;
    
    		if (menuSel == 1) {
    			std::cout << "Taking you to Standard gameplay...\n\n";
    
    			for (int y {}; y < noQuest; ++y)
    				process(y, score, streak, total);
    
    			if (total == 10)
    				std::cout << "Holy crap, a perfect score! You should try the endless mode for an even bigger challenge!\n";
    			else if (total <= 9 && total >= 5)
    				std::cout << "Want to try again for a perfect score?\n";
    			else if (total < 5)
    				std::cout << "Better luck next time..\n";
    			else
    				std::cout << "Looks like somebody did something they shouldn't have.. :(\n";
    
    			pressEnt();
    		}
    
    		if (menuSel == 2) {
    			std::cout << "WARNING: Endless mode is extremely dangerous and hard, if you get a single question wrong, your run ends. Are you sure you want to continue?\n";
    			std::cout << "Y-Continue\nE-Return to Menu\n";
    			std::cout << "Option: ";
    
    			char menuSel2 {};	// alternative menu selection for characters
    
    			std::cin >> menuSel2;
    
    			if (menuSel2 == 'E' || menuSel2 == 'e') {
    				std::cout << "Returning to menu\n";
    				continue;
    			}
    
    			if (menuSel2 == 'Y' || menuSel2 == 'y') {
    				std::cout << "Taking you to endless mode..\n";
    
    				while (true)
    					process(std::rand() % noQuest, score, streak, total);
    			}
    		}
    	}
    }
    Last edited by 2kaud; February 15th, 2024 at 06:17 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3
    Join Date
    Nov 2018
    Posts
    154

    Re: if statement being ignored despite conditions being true

    int menuSel; //menu selection input
    char menuSel2; //alternative menu selection for characters
    ..
    cin >> menuSel;
    ..
    if (menuSel == 2) {
    cin >> menuSel2;
    if (menuSel2 == 'E' || menuSel2 == 'e') {


    cin has the same pitfalls as scanf in C.
    For every data type except "char", the rule is that leading whitespace (spaces, tabs, newlines) are ignored, and trailing whitespace is left on the input stream.

    But if it's a char, then it takes the next char - period.

    Which in your case means menuSel2 is almost certainly the '\n' char left behind after reading menuSel.

    You've basically fallen foul of forgetting what state the input stream is in.

    The short answer is to use this before trying to read a char, just so you know you're not getting a stray input.
    cin.ignore(numeric_limits<streamsize>::max(),'\n')


    > I asked my teacher, and they had no idea.
    What's that phrase?
    Those that can - do, those that can't do - teach, those that can't teach - host talk shows.

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,903

    Re: if statement being ignored despite conditions being true

    For every data type except "char", the rule is that leading whitespace (spaces, tabs, newlines) are ignored, and trailing whitespace is left on the input stream.

    But if it's a char, then it takes the next char - period.
    Not always. Skipping of initial white-space with >> for a char can be compiler dependent. With MS VS2022 this works OK:

    Code:
    #include <iostream>
    
    int main() {
    	int i {};
    	char ch {};
    
    	std::cin >> i;
    	std::cin >> ch;
    
    	std::cout << i << ' ' << ch << '\n';
    }
    as VS2022 defaults to std::skipws for >> char as well as >> int. If a compiler doesn't do this then you can use std::skipws or use std::ws to extract white-space.
    https://cplusplus.com/reference/ios/skipws/
    https://cplusplus.com/reference/istream/ws/

    Consider which forces for VS >> char to behave different to >> int:

    Code:
    #include <iostream>
    
    int main() {
    	int i {};
    	char ch {};
    
    	std::cin >> i;
    	std::cin >> std::noskipws;    // For VS2022 make >> char as not remove initial ws
    	std::cin >> std::ws >> ch;    // Remove any initial ws remaining. May be required for some compilers but will work ok even if not needed
    
    	std::cout << i << ' ' << ch << '\n';
    }
    then std::ws removes the initial ws left by noskipws (or if your compiler has this as default).

    Note that nothing discussed here deals with an error on input (eg entering a non-integer when an integer is required, entering more than one char when just a char is required etc). Handling these sort of issues is a topic in its own right!

    There are also issues with .get() and std::getline() when following a >> as getline() doesn't skip the initial ws but does remove the terminating \n (the opposite of >> (ignoring char issues) ).
    Last edited by 2kaud; February 16th, 2024 at 11:33 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured