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:
#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. I have put one printf under the function to verify that toupper doesn't work.
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()
.
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 */
}
}
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.