0x41414141
0x41414141

Reputation: 364

Converting char into an int not working

I know there are multiple ways about this, but I am trying to get the user to input a character and have that character converted into a specific integer for later use. I am using #define constants to simplify things, in case something needs changing later on. The value that I am getting for userChoice is not 0, 1,or 2 but a large number, so something is wrong.

These are the relevant parts of the code.

    #define ROCK 0
    #define PAPER 1
    #define SCISSORS 2
    void getData (int* userChoice)
{
    char charvalue;
    printf("\n\nEnter the R, P, S, or Q (for quit) ");
    scanf("%c", &charvalue);
    charvalue = toupper(charvalue);
    if (charvalue == 'R')
        *userChoice = ROCK;
    else if (charvalue == 'P')
        *userChoice = PAPER;
    else if (charvalue == 'S')
        *userChoice = SCISSORS;
    else if (charvalue == 'Q')
        exit (1);
    else
        printf("\nerror");
    printf("%d", userChoice);

    return;

}

Upvotes: 3

Views: 236

Answers (2)

Tyler Durden
Tyler Durden

Reputation: 11532

Your input is a pointer to an int, so you must print the value of the pointer *userChoice.

A better practice would be to have the function return the choice as an unsigned int, instead of passing a reference and modifying the reference. In other words, it would be better to use an interface such as:

unsigned int getUserChoice(){ ... etc.

Upvotes: 1

poitroae
poitroae

Reputation: 21367

You print the address of your integer, not the value. To print the value, use *userChoice.

printf("%d", *userChoice);

Upvotes: 3

Related Questions