使用getchar()函数时出现回车也被get到的问题
1.现象
如下面代码所示
// main.c
// Created by Mark观澜
//
#include <stdio.h>
#include <math.h>
int main()
{
char letter;
printf("please input first letter:\n");
while(1)
{
if((letter=getchar())=='#')
break;
switch(letter)
{
case 'm':
printf("monday!\n");break;
case 'w':
printf("wednesday!\n");break;
case 'f':
printf("friday!\n");break;
case 't':
printf("please input the second letter:");
letter=getchar();
if(letter=='u')
printf("tuesday!\n");
else if(letter=='h')
printf("thursday!\n");
else
printf("error!\n");
break;
case 's':
printf("please input the second letter:");
letter=getchar();
if(letter=='a')
printf("saturday!\n");
else if(letter=='h')
printf("sunday!\n");
else
printf("error!\n");break;
default:
printf("error!\n");
}
}
return 0;
}
执行结果如下:
please input first letter:
m
monday!
error!
2.分析:
显然正常打印结果本只有monday。我的理解是缓冲区中有m和"\n"两个符号,getchar()先get到m,打印出monday,然后get到回车的\n,所以打印出error。那么只要在getchar()得到下一个字符前先清空缓冲区就行。
3.改进:
int main()
{
char letter;
printf("please input first letter:");
while(1)
{
if((letter=getchar())=='#')
break;
switch(letter)
{
case 'm':
printf("monday!\n");break;
case 'w':
printf("wednesday!\n");break;
case 'f':
printf("friday!\n");break;
case 't':
printf("please input the second letter:");
getchar();
letter=getchar();
if(letter=='u')
printf("tuesday!\n");
else if(letter=='h')
printf("thursday!\n");
else
printf("error!\n");
break;
case 's':
printf("please input the second letter:");
getchar();
letter=getchar();
if(letter=='a')
printf("saturday!\n");
else if(letter=='u')
printf("sunday!\n");
else
printf("error!\n");break;
default:
printf("error!\n");
}
getchar();
}
return 0;
}