-1

I am trying to set a int to 500, but random numbers such as 22067 come out.

I am trying to make a simple gambling game. Currently, what I'm doing is that I set int gambledMoney = 500; But when I ask to print the 500, it does work but instead it prints 22067. Here is my code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    //introduction
    cout << "Why hello human!\nWelcome to this gambling game where you... gamble!\nTo explain how to play here are the steps:\n\n";
    
    //instructuions
    cout << "You always start with $2000.\nAt the very beginning of each new round, you will be    given choices on the amount of money you will gamble.\n";
    cout << "Then you will gamble against an AI.\nIf you win, you gain the amount that the AI gambled...\nBut if you lose, you lose the money that you gambled.\n";
    cout << "If you reach $500, you lose. Same goes with the AI.\n";
    
    //game start
    cout << "\nNow lets start!\n";
    
    //gamble amount
    string gambleChoice;
    int gambledMoney;
    
    cout << "\nHow much would you like to gamble?";
    cout << "\n A) $500\n B) $750\n C) $1000\n D) $1250\n E) $1500\n F) $1750\n G) $2000\n\n";
    
    //amount chosen
    cin >> gambleChoice;
    
    if (gambleChoice == "a")
    {
        int gambledMoney = 500;
    }

    cout << "\nYou have gambled $" << gambledMoney << "!" << endl;
    
    return 0;
}

Does anyone know why it is not putting 500?

sdvcrs
  • 11

1 Answers1

4

You are declaring two different variables with the name gambledMoney in different scopes, so that one variable "shadows" the other variable with the same name.

The line

int gambledMoney = 500;

will create a new variable with that name, and set it to 500. It won't change the value of the existing variable to 500.

You probably want to change that line to the following:

gambledMoney = 500;

That way, it will change the value of the existing variable, instead of creating a new one.

If you are using the compilers gcc or clang, I recommend that you compile with the -Wshadow command-line option. That way, the compiler will warn you when you create two variables of the same name, so that one shadows the other.

That is not the only compiler warning that I recommend enabling, though. You may want to read this for further information:

Why should I always enable compiler warnings?

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39