Ir ao conteúdo

C++ C++ Enter to continue e Problemas com Loop


Ir à solução Resolvido por isrnick,

Posts recomendados

Postado

Sou iniciante em C++, fiz esse código a caráter de estudo, o programa pede o nome do usuário (playerName) e um número inteiro (zombieCount), e enquanto playerAlive for verdadeiro o zombieCount define o número de rodadas e em cada rodada dois números aleatórios (createZombie, chance) são gerados definindo texto que será mostrado para o usuário e realizando ou não alterações nos int (playerScore, playerSkill, zombieSkill, zombiesKilled).

  

No fim são exibidos os int (zombiesKilled, playerScore) e a string playerName. E o programa pode reiniciar caso o usuário tecle 'y'.

O porém é que quando o programa reinicia ele ignora o "Press [ENTER] to start.". Exibindo ele concatenado com o próximo texto: Press [ENTER] to start.Please enter your name:.

Gostaria que quando o loop for feito o programa esperasse o usuário teclar o enter para prosseguir com a aplicação. Suspeito que quando o usuário tecla "y + ENTER]" para reiniciar o programa esse Enter vai parar no char temp, gerando esse erro.

 


 


   #include <iostream>
    #include <stdlib.h>
    #include <unistd.h>
    #include <time.h>
    #include <windows.h>
    using namespace std;

    int wait = 180;

    int createZombie() {
        if (rand() % 67 > 65) {
            return 21;
        }

        if (rand() % 67 < 10)
            return 11;

        else
            return rand() %10 + 1;
    }

    int chance() {
        return rand() % 100;
    }

    int main() {
        srand(time(NULL));

        char again;

        // game stats
        int playerAlive = true;
        int playerSkill = 9;
        int playerScore = 1;
        string playerName = "";
        int zombieCount = 0;
        int zombiesKilled = 0;
        again = 'y';
        int revive = false;
        char restart;

        int deathlyZombie = false;
        int hugeZombie = false;
        int skinnyZombie = false;


        while (again == 'y') {
            // title
            cout << "Welcome to Zombie War 1.0" << endl << "Press [ENTER] to start.";

            char temp = 'x';
            while (temp != '\n')
                cin.get(temp);


            // player name
            cout << "Please enter your name: ";
            cin >> playerName;

            //ask how many zombies
            cout << "How many zombies do you wish to fight? ";
            cin >> zombieCount;

            cout << "Get ready to fight for your life, " << playerName << "!" << endl;

            // main game loop
            while (playerAlive && zombiesKilled < zombieCount) {

                // create a random zombie
                int zombieSkill = createZombie();
                int luck = chance();


                // battle sequence
                if (zombieSkill > 20) {
                    cout << endl << "Here comes a deathly warrior zombie!!!" << endl;
                    deathlyZombie = true;
                    Sleep (wait);
                }

                else {
                    if (zombieSkill > 10 && zombieSkill < 20) {
                        cout << endl << "Here comes a huge zombie!" << endl;
                        hugeZombie = true;
                        Sleep (wait);
                    }
                    else {
                        cout << endl << "Here comes zombie " << zombiesKilled    + 1    << endl;
                        skinnyZombie = true;
                        Sleep (wait);
                    }
                }

                cout << "Fighting";
                Sleep (wait / 2);
                cout << "." ;
                Sleep (wait / 2);
                cout << "." ;
                Sleep (wait / 2);
                cout << "." << endl;
                Sleep(2000);

                //balance
                if (playerSkill > 50 && luck < 50) {
                    zombieSkill = zombieSkill + 40;
                    playerSkill = playerSkill - 1;
                    cout << "The battle is so hard..." << endl;
                    Sleep (2 * wait);
                }

                if (playerSkill > 100 && luck < 20) {
                    zombieSkill = zombieSkill + 90;
                    cout << "You keep fighting, but the end is coming..." << endl;
                    Sleep (2 * wait);
                }

                if (zombieCount > 100 && luck < 10) {
                    playerSkill = playerSkill - 10;
                    cout << "You suffer from accumulated fatigue...";
                    Sleep (2 * wait);
                }

                if (skinnyZombie == true) {

                    //events
                    if (luck < 5 && playerSkill > 12) {
                        zombieSkill = zombieSkill * 2;
                        zombieCount = zombieCount + 1;
                        cout << "Two zombies appeared this time!!" << endl;
                        Sleep (wait);
                    }

                    if ( luck > 60 && playerSkill > 40) {
                        playerSkill = playerSkill + 1;
                        cout << "Your hatred for zombies gave you strength." << endl;
                        Sleep (wait);
                    }

                    if ( luck > 70 && zombieCount > 10 ) {
                        playerSkill = playerSkill + 1;
                        cout << "The pain you feel increases your focus!!" << endl;
                        Sleep (wait);
                    }

                    if ( luck < 3 ) {
                        playerSkill = playerSkill - 2;
                        cout << "The zombie goes into frenzy!!" << endl;
                        Sleep (wait);
                    }

                    if ( luck < 10 && zombieSkill > 8 ) {
                        cout << "The zombie bit your ear" << endl;
                        Sleep (wait);
                    }

                    if ( playerSkill > zombieSkill ) {
                        skinnyZombie = false;
                    }
                }

                if (hugeZombie == true) {

                    if (luck < 30 && playerScore < 50) {
                        cout << endl << "He eats your arm!" << endl;
                        playerSkill = playerSkill -3;
                        Sleep (wait);
                    }

                    if (luck > 85) {
                        zombieSkill = zombieSkill - 4;
                        cout << "You got a critical hit!!" << endl;
                        Sleep (wait);
                        cout << "The zombie became blind!" << endl;
                        Sleep (wait);
                    }

                    if (luck > 80 && playerSkill > 20) {
                        zombieSkill = zombieSkill - 2;
                        cout << "You cut off the zombie's hands!!" << endl;
                        Sleep (wait);
                    }

                    if (luck < 10) {
                        zombieSkill = zombieSkill + 2;
                        cout << "The zombie kick your face!!" << endl;
                        Sleep (wait);
                    }

                    if (luck > 80 && playerSkill < 11) {
                        zombieSkill = zombieSkill - 2;
                        cout << "The zombie grabbet you!" << endl;
                        Sleep (wait);
                        cout << "You broke free with a butt in the zombie." << endl;
                        Sleep (wait);
                    }

                    if (luck > 98) {
                        playerSkill = playerSkill + 5;
                        cout << "You found a rifle!!" << endl;
                        Sleep (wait);
                    }

                    if (playerSkill > zombieSkill) {
                        hugeZombie = false;
                    }
                }

                if (deathlyZombie == true) {

                    if (luck < 20 ) {
                        zombieSkill = zombieSkill + 2;
                        playerSkill = playerSkill -2;
                        cout << "The zombie break your leg!!" << endl;
                        Sleep (wait);
                        cout << "He threw you on the ground like it was nothing" << endl;
                        Sleep (wait);
                    }

                    if (luck > 20 ) {
                        zombieSkill = zombieSkill + 1;
                        cout << "You got away with a blow." << endl;
                        Sleep (wait);
                        cout << "He predicted yours movements!!" << endl;
                        Sleep (wait);
                    }

                    if (playerSkill > 20 && luck > 80) {
                        playerSkill = playerSkill +2;
                        cout << "You still have not given up hope.";
                        Sleep (wait);
                    }

                    if (playerSkill > zombieSkill) {
                        cout << "The deathly warrior zombie will remember you" << endl;
                        deathlyZombie = false;
                        Sleep (wait);
                    }
                }

                if (hugeZombie == true || deathlyZombie == true) {
                    if (luck > 85) {
                        playerSkill = playerSkill +1;
                        zombieSkill = zombieSkill -1;
                        cout << endl << "The zombie tries to grab you.";
                        Sleep (wait);
                        cout << endl << "You dodge and knock him down"<< endl;
                        Sleep (wait);
                    }

                    if ( luck > 10 && luck < 20 ) {
                        cout << "You lost one of yours tooth!" << endl;
                        Sleep (wait);
                    }
                }

                if (luck > 50) {

                    if (luck > 85 && zombieSkill < 30) {
                        playerSkill = playerSkill + 1;
                        cout << "You ate some cookies! " << endl;
                        Sleep (wait);
                    }

                    if (luck > 99 && playerSkill > 30) {
                        revive = true;
                        cout << "You found a mysterious red ring!!" << endl;
                        Sleep (3 * wait);
                    }

                    if (luck > 92 && zombieCount > 10) {
                        zombieSkill = zombieSkill - 2;
                        playerSkill = playerSkill + 1;
                        cout << endl << "You cut off his leg!! " << endl;
                        Sleep (wait);
                        cout << "You found some bandage!" << endl;
                        Sleep (wait);
                    }
                }

                if (luck < 5) {
                    zombieSkill = zombieSkill + 2;
                    cout << "The zombie has a sword!" << endl;
                    Sleep (wait);
                }

                Sleep (wait);

                //zombie killed the player
                if (playerSkill < zombieSkill) {
                    playerAlive = false;
                    cout << "You have died." << endl;
                    Sleep (5 * wait);
                    if (revive == true) {
                        playerAlive = true;
                        cout << "The mysterious red ring revive you!!" << endl;
                        Sleep (wait);
                        cout << "The ring became useless!!" << endl;
                        Sleep (wait);
                    }
                }


                // player killed the zombie
                else {
                    if (playerSkill - zombieSkill > 11){
                        cout << "You blew the zombie's head!"<< endl;
                        playerScore = playerScore + 1;
                        Sleep (2 * wait);
                    }
                    if (playerSkill - zombieSkill > 7 && playerSkill - zombieSkill < 12) {
                        cout << "You wasted the zombie!" << endl;
                        playerScore = playerScore + 2;
                        Sleep (2 * wait);
                    }

                    if (playerSkill - zombieSkill > 5 && playerSkill - zombieSkill < 😎 {
                        cout << "You decapitated the zombie!" << endl;
                        playerScore = playerScore + 3;
                        Sleep (2 * wait);
                    }

                    if (playerSkill - zombieSkill > 2 && playerSkill - zombieSkill < 6 ) {
                        cout << "You killed the zombie!" << endl;
                        playerScore = playerScore + 4;
                        Sleep (2 * wait);
                    }

                    if (playerSkill > zombieSkill && zombieSkill > 10 && zombieSkill <20) {
                        playerScore = playerScore + 5;
                        Sleep (2 * wait);
                    }

                    if (playerSkill > zombieSkill && zombieSkill > 20) {
                        playerScore = playerScore + 20;
                        Sleep (2 * wait);
                    }

                    else if (playerSkill - zombieSkill < 3){
                        cout << "You killed the zombie, but suffered injuries." << endl;
                        playerSkill = playerSkill - 1;
                        Sleep (2 * wait);
                    }

                    zombiesKilled++;
                }

                cout << endl;
                Sleep (3000);
            }


            // end game
            if (zombiesKilled == zombieCount) {
                // victory
                cout << "You have survived the onslaught! \n" <<
                        "Congratulations " + playerName + "!" << endl;
            }
            else {
                // lost
                cout << "You did not survive the zombie war. \n" <<
                        "Try to come back stronger next time " + playerName + "!" << endl;
            }
            Sleep (wait);
            cout << "Zombies killed: " << zombiesKilled << endl;
            cout << "Your power this round: " << playerSkill << endl;
            cout<< "Final score: " << playerScore << endl << endl;
            cout << "Do you wanna play again? y/n" << endl;
            cin >> restart;

        while ( restart != 'y' || restart != 'n' ) {

            if ( restart == 'n' ){
                again = 'n';
                cout << "Thanks for playing!!";
                playerAlive = false;
                return 0;
                break;
            }

            if ( restart == 'y') {
                playerAlive = true;
                zombiesKilled = 0;
                zombieCount = 0;
                skinnyZombie = false;
                hugeZombie = false;
                deathlyZombie = false;
                break;
            }
            else {
                cout << "Please insert a valid character! \n";
                cin >> restart;
            }

            }
        }
        return 0;
}

 

Postado

Coloque um cin.ignore(); no fim do ciclo while pra limpar o caractere nova linha '\n' que sobrou no stdin (entrada padrão) do último cin executado no programa, assim ele não será carapturado pelo seu cin.get(temp) ao invés de esperar que o usuário digite aperte um novo Enter.

Postado
19 horas atrás, isrnick disse:

Coloque um cin.ignore(); no fim do ciclo while pra limpar o caractere nova linha '\n' que sobrou no stdin (entrada padrão) do último cin executado no programa, assim ele não será carapturado pelo seu cin.get(temp) ao invés de esperar que o usuário digite aperte um novo Enter.


Para mim você não foi muito claro em como usar o cin.ignore(), tive que pesquisar e descobri que era para adicionar ele logo abaixo do "cin >> restart;":

 

cin >> restart;

cin.ignore();

 

Resolveu o problema, agora outra coisa que quero alterar no código é :

 while ( restart != 'y' || restart != 'n' ) {

            if ( restart == 'n' ){
                again = 'n';
                cout << "Thanks for playing!!";
                playerAlive = false;
                return 0;
                break;
            }

            if ( restart == 'y') {
                playerAlive = true;
                zombiesKilled = 0;
                zombieCount = 0;
                skinnyZombie = false;
                hugeZombie = false;
                deathlyZombie = false;
                break;
            }
            else {
                cout << "Please insert a valid character! \n";
                cin >> restart;
			cin.ignore();
            }

            }

 

Quando o usuário digita qualquer tecla que não seja 'y' ou 'n' o else é ativado exibindo a mensagem "Please insert a valid character!".

 

Porém se ao invés de apenas um caractere o usuário digitar (shampu) uma palavra de 6 letras, 6 mensagens serão exibidas na tela, uma para cada letra que não for 'y' ou 'n'. Como corrigir isso para que não importando o número de caracteres usuário digitar apenas uma mensagem de alerta seja exibida na tela?

  • Solução
Postado

ignore() pode receber 2 parâmetros, o número máximo de caracteres a serem ignorados, e um caractere delimitador que indica quando parar de ignorar:

https://en.cppreference.com/w/cpp/io/basic_istream/ignore

 

Então se usar cin.ignore(5, '\n') por exemplo vai ignorar até 5 caracteres ou até encontrar um caractere nova linha, o que ocorrer primeiro.

 

E para ignorar qualquer quantidade de caracteres pode usar numeric_limits<streamsize>::max(), da biblioteca <limits>, para obter o tamanho máximo possível para uma stream. E o comando ficaria assim:

 

#include <limits>


...


cin.ignore(numeric_limits<streamsize>::max(), '\n');

 

Postado

Tentei adicionar o <limits>, acontece que ele deu problema com o <windows.h>, ambos utilizam terminações como max e min em suas bibliotecas, para resolver precisava usar #infdef, #define, #endif (meio que definindo qual é qual). Coisas complicadas até demais para mim no momento, então optei por abandonar o windows.h.

Só usava o windows.h por causa de Sleep, que por sua vez eu usava por não conseguir usar o sleep normal (vários post na internet estão desatualizados e para usuários com esse problema eles indicam usar o windows.h) no fim descobri que a forma correta no C++ é usleep.

 

Agora vamos para o código:

	#include <iostream>
	#include <stdlib.h> // alterações no início e no fim
	#include <unistd.h>
	#include <time.h>
	#include <limits>

	using namespace std;

	int wait = 50000;

	int createZombie() {
		if (rand() % 67 > 65) {
			return 21;
		}

		if (rand() % 67 < 10)
			return 11;

		else
			return rand() %10 + 1;
	}

	int chance() {
		return rand() % 100;
	}

	int main() {
		srand(time(NULL));

		char again;

		// game stats
		int playerAlive = true;
		int playerSkill = 9;
		int playerScore = 1;
		string playerName = "";
		int zombieCount = 0;
		int zombiesKilled = 0;
		again = 'y';
		int revive = false;
		char restart;

		int deathlyZombie = false;
		int hugeZombie = false;
		int skinnyZombie = false;


		while (again == 'y') {
			// title
			cout << "Welcome to Zombie War 1.0" << endl << "Press [ENTER] to start.";

			char temp = 'x';
			while (temp != '\n')
			    cin.get(temp);

			// player name
			cout << "Please enter your name: ";
			cin >> playerName;

			//ask how many zombies
			cout << "How many zombies do you wish to fight? ";
			cin >> zombieCount;

			cout << "Get ready to fight for your life, " << playerName << "!" << endl;

			// main game loop
			while (playerAlive && zombiesKilled < zombieCount) {

				// create a random zombie
				int zombieSkill = createZombie();
				int luck = chance();


				// battle sequence
				if (zombieSkill > 20) {
					cout << endl << "Here comes a deathly warrior zombie!!!" << endl;
					deathlyZombie = true;
					usleep (wait);
				}

				else {
					if (zombieSkill > 10 && zombieSkill < 20) {
						cout << endl << "Here comes a huge zombie!" << endl;
						hugeZombie = true;
						usleep (wait);
					}
					else {
						cout << endl << "Here comes zombie " << zombiesKilled	+ 1	<< endl;
						skinnyZombie = true;
						usleep (wait);
					}
				}

				cout << "Fighting";
				usleep (wait / 2);
				cout << "." ;
				usleep (wait / 2);
				cout << "." ;
				usleep (wait / 2);
				cout << "." << endl;
				usleep(wait);

				//balance
				if (playerSkill > 50 && luck < 50) {
					zombieSkill = zombieSkill + 40;
					playerSkill = playerSkill - 1;
					cout << "The battle is so hard..." << endl;
					usleep (2 * wait);
				}

				if (playerSkill > 100 && luck < 20) {
					zombieSkill = zombieSkill + 90;
					cout << "You keep fighting, but the end is coming..." << endl;
					usleep (2 * wait);
				}

				if (zombieCount > 100 && luck < 10) {
					playerSkill = playerSkill - 10;
					cout << "You suffer from accumulated fatigue...";
					usleep (2 * wait);
				}

				// two
				if (hugeZombie == true || deathlyZombie == true) {
					if (luck > 85) {
						playerSkill = playerSkill +1;
						zombieSkill = zombieSkill -1;
						cout << endl << "The zombie tries to grab you.";
						usleep (wait);
						cout << endl << "You dodge and knock him down"<< endl;
						usleep (wait);
					}

					if ( luck > 10 && luck < 20 ) {
						cout << "You lost one of yours tooth!" << endl;
						usleep (wait);
					}
				}

				// one
				if (skinnyZombie == true) {

					//events
					if (luck < 5 && playerSkill > 12) {
						zombieSkill = zombieSkill * 2;
						zombieCount = zombieCount + 1;
						cout << "Two zombies appeared this time!!" << endl;
						usleep (wait);
					}

					if ( luck > 60 && playerSkill > 40) {
						playerSkill = playerSkill + 1;
						cout << "Your hatred for zombies gave you strength." << endl;
						usleep (wait);
					}

					if ( luck > 70 && zombieCount > 10 ) {
						playerSkill = playerSkill + 1;
						cout << "The pain you feel increases your focus!!" << endl;
						usleep (wait);
					}

					if ( luck < 3 ) {
						playerSkill = playerSkill - 2;
						cout << "The zombie goes into frenzy!!" << endl;
						usleep (wait);
					}

					if ( luck < 10 && zombieSkill > 8 ) {
						cout << "The zombie bit your ear" << endl;
						usleep (wait);
					}

					if ( playerSkill > zombieSkill ) {
						skinnyZombie = false;
					}
				}

				if (hugeZombie == true) {

					if (luck < 30 && playerScore < 50) {
						cout << endl << "He eats your arm!" << endl;
						playerSkill = playerSkill -3;
						usleep (wait);
					}

					if (luck > 85 && zombieSkill < 14 && playerScore > 5) {
						zombieSkill = zombieSkill - 4;
						cout << "You got a critical hit!!" << endl;
						usleep (wait);
						cout << "The zombie became blind!" << endl;
						usleep (wait);
					}

					if (luck > 80 && playerSkill > 20) {
						zombieSkill = zombieSkill - 2;
						cout << "You cut off the zombie's hands!!" << endl;
						usleep (wait);
					}

					if (luck < 10) {
						zombieSkill = zombieSkill + 2;
						cout << "The zombie kick your face!!" << endl;
						usleep (wait);
					}

					if (luck > 80 && playerSkill < 11) {
						zombieSkill = zombieSkill - 2;
						cout << "The zombie grabbet you!" << endl;
						usleep (wait);
						cout << "You broke free with a butt in the zombie." << endl;
						usleep (wait);
					}

					if (luck > 98) {
						playerSkill = playerSkill + 5;
						cout << "You found a rifle!!" << endl;
						usleep (wait);
					}

					if (playerSkill > zombieSkill) {
						hugeZombie = false;
					}
				}

				if (deathlyZombie == true) {

					if (luck < 20 ) {
						zombieSkill = zombieSkill + 2;
						playerSkill = playerSkill -2;
						cout << "The zombie break your leg!!" << endl;
						usleep (wait);
						cout << "He threw you on the ground like it was nothing" << endl;
						usleep (wait);
					}

					if (luck > 20 ) {
						zombieSkill = zombieSkill + 1;
						cout << "You got away with a blow." << endl;
						usleep (wait);
						cout << "He predicted yours movements!!" << endl;
						usleep (wait);
					}

					if (playerSkill > 20 && luck > 80) {
						playerSkill = playerSkill +2;
						cout << "You still have not given up hope.";
						usleep (wait);
					}

					if (playerSkill > zombieSkill) {
						cout << "The deathly warrior zombie will remember you" << endl;
						deathlyZombie = false;
						usleep (wait);
					}
				}
				// others

				if (luck > 50) {

					if (luck > 85 && zombieSkill < 30) {
						playerSkill = playerSkill + 1;
						cout << "You ate some cookies! " << endl;
						usleep (wait);
					}

					if (luck > 99 && playerSkill > 30) {
						revive = true;
						cout << "You found a mysterious red ring!!" << endl;
						usleep (3 * wait);
					}

					if (luck > 92 && zombieCount > 10) {
						zombieSkill = zombieSkill - 2;
						playerSkill = playerSkill + 1;
						cout << endl << "You cut off his leg!! " << endl;
						usleep (wait);
						cout << "You found some bandage!" << endl;
						usleep (wait);
					}
				}

				if (luck < 5) {
					zombieSkill = zombieSkill + 2;
					cout << "The zombie has a sword!" << endl;
					usleep (wait);
				}

				usleep (wait);

				//zombie killed the player
				if (playerSkill < zombieSkill) {
					playerAlive = false;
					cout << "You have died." << endl;
					usleep (5 * wait);
					if (revive == true) {
						playerAlive = true;
						cout << "The mysterious red ring revive you!!" << endl;
						usleep (wait);
						cout << "The ring became useless!!" << endl;
						usleep (wait);
					}
				}


				// player killed the zombie
				else {
					if (playerSkill - zombieSkill > 11){
						cout << "You blew the zombie's head!"<< endl;
						playerScore = playerScore + 1;
						usleep (2 * wait);
					}
					if (playerSkill - zombieSkill > 7 && playerSkill - zombieSkill < 12) {
						cout << "You wasted the zombie!" << endl;
						playerScore = playerScore + 2;
						usleep (2 * wait);
					}

					if (playerSkill - zombieSkill > 5 && playerSkill - zombieSkill < 8) {
						cout << "You decapitated the zombie!" << endl;
						playerScore = playerScore + 3;
						usleep (2 * wait);
					}

					if (playerSkill - zombieSkill > 2 && playerSkill - zombieSkill < 6 ) {
						cout << "You killed the zombie!" << endl;
						playerScore = playerScore + 4;
						usleep (2 * wait);
					}

					if (playerSkill > zombieSkill && zombieSkill > 10 && zombieSkill <20) {
						playerScore = playerScore + 5;
						usleep (2 * wait);
					}

					if (playerSkill > zombieSkill && zombieSkill > 20) {
						playerScore = playerScore + 20;
						usleep (2 * wait);
					}

					else if (playerSkill - zombieSkill < 3){
						cout << "You killed the zombie, but suffered injuries." << endl;
						playerSkill = playerSkill - 1;
						usleep (2 * wait);
					}

					zombiesKilled++;
				}

				cout << endl;
				usleep (wait * 10);
			}


			// end game
			if (zombiesKilled == zombieCount) {
				// victory
				cout << "You have survived the onslaught! \n" <<
						"Congratulations " + playerName + "!" << endl;
			}
			else {
				// lost
				cout << "You did not survive the zombie war. \n" <<
						"Try to come back stronger next time " + playerName + "!" << endl;
			}
			usleep (wait);
			cout << "Zombies killed: " << zombiesKilled << endl;
			cout << "Your power this round: " << playerSkill << endl;
			cout<< "Final score: " << playerScore << endl << endl;
			cout << "Do you wanna play again? y/n" << endl;
			cin >> restart;
			cin.ignore(numeric_limits<streamsize>::max(), '\n');


		while ( restart != 'y' || restart != 'n' ) {

			if ( restart == 'n' ){
				again = 'n';
				cout << "Thanks for playing!!";
				playerAlive = false;
				return 0;
				break;
			}

			if ( restart == 'y') {

				playerAlive = true;
				zombiesKilled = 0;
				zombieCount = 0;
				skinnyZombie = false;
				hugeZombie = false;
				deathlyZombie = false;
				cout << "Restart y on";
				break;
			}
			else {
				cout << "Please insert a valid character! \n";
				cin >> restart;
				cin.ignore(numeric_limits<streamsize>::max(), '\n');

			}
		}
		return 0;
}
	}

 

"Porém se ao invés de apenas um caractere o usuário digitar (shampu) uma palavra de 6 letras, 6 mensagens serão exibidas na tela, uma para cada letra que não for 'y' ou 'n'. Como corrigir isso para que não importando o número de caracteres usuário digitar apenas uma mensagem de alerta seja exibida na tela?"

 

Resolveu esse problema porém o loop não está mais funcionando...

o if (restart == 'n') continua funcionando, porém o if (restart == 'y') apesar de aparentemente executar os códigos, não está continuando com o loop.

 

Postado

@Joanderson Pereira Olá

Atualizando...

Você colocou o return 0; dentro do while mais externo, só isso

 

Pode não ser só esse o problema, mas esse é um problema q deve ser resolvido

Testa para ver se tá tudo ok, tirando o comando return 0; de dentro do while mais externo

 

Obs: Belo código esse seu!

Postado

return 0; está dentro do ciclo while mas não deveria, mude o return 0; de posição para ser o último comando do main().

Com um código bem indentado fica fácil ver esse tipo de problema.

  • Curtir 1
  • 2 semanas depois...

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...