Text adventure. C++, do stuck in a loop

Hello,

I am having some basic trouble with my c++ code. My do loop is getting stuck in an infinet loop and I cant figure out why. Does anyone know why this happens?

#include

#include <stdlib.h>

int main () {

int user = 0;

char cont = 'y';

std::cout << “Welcome.\n”;

std::cout << “Do you wish to start the game?.\n”;

std::cout << "Press y to continue and x to exit.\n";

 std::cout << "  > ";

 std::cin >> cont;

if (cont == 'y') {

  std::cout << "You have started the game.! Have fun.\n";

  std::cout << "You wake up alone in a deserted island.\n";

  std::cout << "You cannot remember anything.\n";

  std::cout << "Near you there is a sword and a hammer.\n";

  std::cout << "Whic one do you decide to take with you?.\n";

  std::cout << "1)Sword.\n";

  std::cout << "2)Hammer.\n";

} else {

  std::cout << "Game closed sucessfully.\n";

}

    do {

    std::cin >> user;

} while (user != 1 && user != 2);

 if (user == 1){

   std::cout << "You have picked up the sword and went left.\n";

 } else {

   std::cout << "You have picked up the hammer and went right.\n";

 }

}

Hey there and welcome to the community!! :slightly_smiling_face:

What are you entering to get stuck in a loop? If I enter 1 or 2 than it terminates for me.

User can never be equal to 1 and 2 at the same time
you want to check if user is one or two

Given this is an and not an or, than shouldn’t a condition of or 2 return false while anything else return true?

#include <stdio.h>
#define check(x) x != 1 && x != 2

int main(void) {
  printf("%d\n", check(1)); // evaluated to false
  printf("%d\n", check(2)); // evaluated to false

  printf("%d\n", check(3)); // evaluates to true
}

There was something wrong with the code academy compiler it seems but it is working today. I tryed another compiler yesterday and it worked for me too :stuck_out_tongue: . Gave me a head scratcher for an hour.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.