繁体   English   中英

toupper function 不适用于指针取消引用?

[英]toupper function doesn't work with pointer dereference?

我正在编写一个程序来确定输入是白面包还是甜面包,并将确定面包类型的值作为指针传递给 function:

#include <ctype.h>

void WhiteSweetChoosing(char *orWhiteSweet);

int main(){

    char orWhiteSweet ,isDouble, isManual;
    WhiteSweetChoosing(&orWhiteSweet);
    printf("%c", orWhiteSweet);

    return 0;
}

void WhiteSweetChoosing(char *orWhiteSweet){
    printf("Please enter your bread type\n");
    printf("W for white and S for sweet:");
    scanf(" %c", orWhiteSweet);
    *orWhiteSweet = toupper(*orWhiteSweet);

    while(*orWhiteSweet != 'S' && *orWhiteSweet != 'W'){
        printf("Please enter valid character\n");
        printf("W for white and S for sweet:");
        scanf(" %c", orWhiteSweet);
    }

}

但是,这不起作用,因为 toupper function 似乎没有将新值分配给取消引用的指针。 我在 function 下放了一个 printf 以验证 toupper 不起作用。

但是当我将值分配给一个新变量而不是旧的取消引用指针本身时,它开始工作:

void WhiteSweetChoosing(char *orWhiteSweet){
    printf("Please enter your bread type\n");
    printf("W for white and S for sweet:");
    scanf(" %c", orWhiteSweet);
    char WorS = toupper(*orWhiteSweet);

    while(WorS != 'S' && WorS != 'W'){
        printf("Please enter valid character\n");
        printf("W for white and S for sweet:");
        scanf(" %c", orWhiteSweet);
        WorS = toupper(*orWhiteSweet);
    }

}

如果有人能解释原因,我将不胜感激,谢谢

您忘记为第二个或以后的scanf()读取的值应用toupper

void WhiteSweetChoosing(char *orWhiteSweet){
    printf("Please enter your bread type\n");
    printf("W for white and S for sweet:");
    scanf(" %c", orWhiteSweet);
    *orWhiteSweet = toupper(*orWhiteSweet);

    while(*orWhiteSweet != 'S' && *orWhiteSweet != 'W'){
        printf("Please enter valid character\n");
        printf("W for white and S for sweet:");
        scanf(" %c", orWhiteSweet);
        *orWhiteSweet = toupper(*orWhiteSweet); /* add this */
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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