8 Ball Exercise Question

Was doing the 8-Ball probably just fine but wanted to try something extra to see how it would work.
Wanted to have the program ask the user what their question was. It would store it, but ultimately not use it. Just to make it seem like you were actually asking something. When I run the code though, it never prompts the user to enter a question and just runs the if statements right away. I rearranged some of the code but I’m not sure what’s going on. Is there an order about IF statements that I have not learned yet? Curious.

#include
#include

int main() {

std::string user_input;

std::cout << “Ask Magic 8-Ball a Question!\n”;
std::cin >> user_input;

std::cout << "MAGIC 8-BALL: ";

srand(time(NULL));

int answer = std::rand() % 10;

if (answer == 0) {
std::cout << “It is certain\n”;
}

else if (answer == 1) {
std::cout << “It is decidedly so.\n”;
}

else if (answer == 2) {
std::cout << “Without a doubt.\n”;
}

else if (answer == 3) {
std::cout << “Yes - definitely.\n”;
}

else if (answer == 4) {
std::cout << “Ask again later.\n”;
}

else if (answer == 5) {
std::cout << “Cannot predict now.\n”;
}

else if (answer == 6) {
std::cout << “My reply is no.\n”;
}

else if (answer == 7) {
std::cout << “Don’t count on it.\n”;
}

else if (answer == 8) {
std::cout << “Outlook good.\n”;
}

else if (answer == 9) {
std::cout << “Outlook not so good.\n”;
}

else {
std::cout << “Very doubtful\n”;
}

}

I tried the same thing some time ago. The problem is not with your code. If you run it in another environment like on repl.it. You’ll see that it works as you would expect. The issue is that in the environment set up by Codecademy for this lesson, std::cin is disabled. The computer just skips over that line without executing it. I ran your code on repl.it, and it works perfectly! Happy Coding!

P.S. When you paste your code into a post on the forum, please click the </> icon first. Then paste your code in the space indicated. That will preserve your formatting, and make your code much easier to read.

1 Like

Thanks, I was wondering if that was the case as I have noticed a few other instances where I’m trying some code that I think would work but it does not within the lesson environment. Good to know that I’m not crazy. I will use the code tool for posts from now on too!

1 Like