【问题标题】:toupper function doesn't work with pointer dereference?toupper 函数不适用于指针取消引用?
【发布时间】:2020-12-06 06:29:37
【问题描述】:

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

#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 函数似乎没有将新值分配给取消引用的指针。我在函数下放了一个 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);
    }

}

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

【问题讨论】:

    标签: c


    【解决方案1】:

    您忘记将toupper 应用于第二个或更晚scanf() 读取的值。

    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 */
        }
    
    }
    

    【讨论】:

    • 谢谢!我没有注意到这样一个不经意的错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 2021-07-25
    • 2017-11-03
    • 2010-10-20
    • 1970-01-01
    相关资源
    最近更新 更多