问题描述
当我在我的代码中使用scanf(%c,y)1中的%c时。它没有用。但是当我用%s替换%c时。有效。为什么?请尽快回答。我明天有考试,我需要为它辩护。
继承我的整个代码。
when i used %c in scanf("%c",y)1 in my code. it didnt work. but when i replaced %c with %s. it worked. why? please answer asap. i have exam tomorrow and i need to defend it.
heres my entire code.
#include<stdio.h>
#include<conio.h>
void main(){
int x; //sport
char y;//role,event,style,etc
clrscr();
printf("enter a number between 1-5:");
scanf("%d",&x);
if(x==1){
printf("basketball\n");
printf("enter a or b:");
scanf("%s",&y);
if(y=='A'||y=='a'){
printf("forward");
}
else if(y=='B'||y=='b'){
printf("guard");
}
else{
printf("invalid input");
}
}
else if(x==2){
printf("badminton\n");
printf("enter a or b:");
scanf("%s",&y);
if(y=='A'||y=='a'){
printf("singles");
}
else if(y=='B'||y=='b'){
printf("doubles");
}
else{
printf("invalid input");
}
}
else if(x==3){
printf("baseball\n");
printf("enter a or b:");
scanf("%s",&y);
if(y=='A'||y=='a'){
printf("catcher");
}
else if(y=='B'||y=='b'){
printf("pitcher");
}
else{
printf("invalid input");
}
}
else if(x==4){
printf("swimming\n");
printf("enter a or b:");
scanf("%s",&y);
if(y=='A'||y=='a'){
printf("back stroke");
}
else if(y=='B'||y=='b'){
printf("butterfly");
}
else{
printf("invalid input");
}
}
else if(x==5){
printf("track and field\n");
printf("enter a or b:");
scanf("%s",&y);
if(y=='A'||y=='a'){
printf("discus throw");
}
else if(y=='B'||y=='b'){
printf("100m dash");
}
else{
printf("invalid input");
}
}
else{
printf("invalid input");
}
getch();
}
推荐答案
scanf("%s", &y);
如果 y
被声明为 char
。
您应该始终检查 scanf
功能结果(它应该是 1
case)。
你必须考虑缓冲控制台输入,即 scanf
不返回直到你按回车。
请考虑发布更有意义的信息,它不起作用真的很差。
if y
is declared as char
.
You should always check scanf
function result (it should be 1
in your case).
You have to consider that console input is buffered, that is, scanf
doesn't return until you press return.
Please consider posting more meaningful info, "It doesn't work" is really poor.
这篇关于为什么%s在scanf中使用而不是%c(“%c”,y);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!