简体   繁体   中英

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;

}

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

printf("%d", *userChoice);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM