求大神赐教!为什么case‘t’的情况只能出现一个正确的!错在哪了?
void main()// 请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。{
char ch;
printf("please input the frist word of someday!\n");
while ((ch = getchar()) != 'y')
{
switch (ch)
{
case 'm': printf("monday\n"); break;
case 'f': printf("firday\n"); break;
case 'w': printf("wednesday\n"); break;
case 't': printf("please input the second word of someday!\n");
if ((ch = getchar()) == 'u')
{
printf("tuesday\n");
}
else if ((ch = getchar()) == 'h')
{
printf("thursday\n");
}
else
printf("input error!!!\n");
break;
case 's': printf("please input the second word of someday!\n");
if ((ch = getchar()) == 'a')
{
printf("saturday\n");
}
else if ((ch = getchar()) == 'u')
{
printf("sunday\n");
}
else
printf("input error!!!\n");
break;
}
}
} #include<stdio.h>
int main()// 请输入星期几的第一个字母来判断一下是星期几,如果第一个字母一样,则继续判断第二个字母。
{
char ch;
printf("please input the first letter of someday!\n");
while ((ch = getchar()) != 'y')
{
fflush(stdin);
switch (ch)
{
case 'm':
printf("monday\n");
printf("please input the first letter of someday!\n");break;
case 'f':
printf("friday\n");
printf("please input the first letter of someday!\n");break;
case 'w':
printf("wednesday\n");
printf("please input the first letter of someday!\n");break;
case 't':
printf("please input the second letter of someday!\n");
if ( (ch = getchar()) == 'u')
printf("tuesday\n");
else if (ch == 'h')
printf("thursday\n");
else
printf("input error!!!\n");
printf("please input the first letter of someday!\n");
break;
case 's':
printf("please input the second letter of someday!\n");
if ((ch = getchar()) == 'a')
printf("saturday\n");
else if (ch == 'u')
printf("sunday\n");
else
printf("input error!!!\n");
printf("please input the first letter of someday!\n");
break;
}
}
return 0;
}写代码,至少用 C11 的标准,int main() return 0;
多重输入还是用 scanf() 或者 scanf_s()比较安全。问题与输入缓冲区有关,所以前面 fflush(stdin) 把缓冲区清空。 if () else if() 是连续的,会执行 if() 的条件判断,如果不符合,执行下一个 else if() 的判断。
getchar() 返回当前指针指向缓冲区的字符,然后指针完后移动。你输入的只有单一字符,所以下一个是回车。你用两个 getchar() 就指向换行了。
getchar() 的功能不是要求输入,而是从输入缓冲区里提出一个元素。 claws0n 发表于 2018-10-7 16:31
写代码,至少用 C11 的标准,int main() return 0;
多重输入还是用 scanf() 或者 scanf_s()比较安全。问 ...
好的 非常感谢您! claws0n 发表于 2018-10-7 16:31
写代码,至少用 C11 的标准,int main() return 0;
多重输入还是用 scanf() 或者 scanf_s()比较安全。问 ...
貌似这样修改还是不行啊,运行起来结果比没改之前还糟糕,怎么破? JuniorHu 发表于 2018-10-7 16:49
貌似这样修改还是不行啊,运行起来结果比没改之前还糟糕,怎么破?
你直接用我的代码吗?please input the first letter of someday!
m
monday
please input the first letter of someday!
f
friday
please input the first letter of someday!
w
wednesday
please input the first letter of someday!
t
please input the second letter of someday!
u
tuesday
please input the first letter of someday!
t
please input the second letter of someday!
h
thursday
please input the first letter of someday!
s
please input the second letter of someday!
a
saturday
please input the first letter of someday!
s
please input the second letter of someday!
u
sunday
please input the first letter of someday!
页:
[1]