[英]toupper function doesn't work with pointer dereference?
I am writing a program that determines whether the input is white or sweet bread, and I pass the value that determines the bread type to a function as a pointer:我正在编写一个程序来确定输入是白面包还是甜面包,并将确定面包类型的值作为指针传递给 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);
}
}
However, this doesn't work as the toupper function doesn't seem to assign the new value to the dereferenced pointer.但是,这不起作用,因为 toupper function 似乎没有将新值分配给取消引用的指针。 I have put one printf under the function to verify that toupper doesn't work.
我在 function 下放了一个 printf 以验证 toupper 不起作用。
But when I assign the value to a new variable instead of the old dereferenced pointer itself, it started to work:但是当我将值分配给一个新变量而不是旧的取消引用指针本身时,它开始工作:
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);
}
}
I would be appreciated if someone is kind enough to explain why, thanks如果有人能解释原因,我将不胜感激,谢谢
You forget to apply toupper
for values read by second or later scanf()
.您忘记为第二个或以后的
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.