帮我看下这个c语言程序哪里不对

[复制链接]
查看11 | 回复2 | 2008-12-3 09:29:33 | 显示全部楼层 |阅读模式
#include
#include"math.h"
void main()
{char letter;
printf("Please input the first number\n");
scanf("%c",&letter);
{switch(letter)
{case('M'):printf("Monday\n");break;
case('T'):printf("please input the second number\n");

if((letter=getchar())=='u')
printf("Tuesday\n");
else if((letter=getchar())=='h')
printf("Thursday\n");
else
printf("error\n");
break;
case('W'):printf("Wednesday\n");break;
case('F'):printf("Friday\n");break;
case('S'):printf("Please input the second number\n");
if ((letter=getchar())=='a')
printf("Saturday\n");
else if((letter=getchar())=='u')
printf("Sunday\n");
else
printf("error\n");
break;
default:printf("data error\n");
}
}
}
当输入为‘S'时,它会提示你输入第二个字母,再输入u时,显示sunday,但输入a时,应该显示saturday,但为什么却显示error。当第一次输入T时同理

回复

使用道具 举报

千问 | 2008-12-3 09:29:33 | 显示全部楼层
getchar()这个函数是会读进任何的输入的,当你第一个输入S的时候,肯定也会输入一个回车做为输入结束的标志,而这个回车也会存在缓冲区内,当你getchar()时,就会把这个回车输入,所以当然不匹配了,就会出错。解决方法:在你打印出要求用户输如第二个字符的语句后加上getchar();将上次输入的回车吃掉,就可以了。case('S'):printf("Please input the second number\n");getchar();...
回复

使用道具 举报

千问 | 2008-12-3 09:29:33 | 显示全部楼层
帮你解释如下:scanf("%c",&letter); //这里留下了一个回车符在缓冲区里......case('T'):printf("please input the second number\n"); if((letter=getchar())=='u') //这里getchar()得到的是回车符printf("Tuesday\n...
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行