使用getchar与scanf联合使用时的注意要点
在程序中若先使用了scanf()进行了输入读取,再使用getchar进行字符读取,则会使程序输出结果出现问题:
这是因为在scanf()进行输入读取后,会把换行符保留在缓冲区,作为下次输入的读取,此时使用getchar进行输入字符的读取就会出现将缓冲区的换行符作为字符读取而导致程序错误;
此时的解决办法有二:
1、不使用scanf();
2、每次调用scanf()时后紧跟一getchar(),作为对scanf()的”影响消除”;
下列两个示例以加深记忆:
输入n个字符,判断并统计输入的各类字符数量
1、错误示例:
#include<stdio.h>
int main() //统计英文字母和数字字符
{
int n,i;
char ch;
int Num_char=0,Num_Num=0,Num_other=0;
printf("please enter the number of characters:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ch = getchar();
if(ch>='a' && ch<='z' || ch>='A' && ch<='Z')
{
Num_char++;
}
else if(ch>='0' && ch<='9')
{
Num_Num++;
}
else
{
Num_other++;
}
}
printf("The number of letter is %d\nThe number of Number is %d\nThe number of other is %d",Num_char,Num_Num,Num_other);
return 0;
}
程序运行结果:
错误
2、正确示例:
#include<stdio.h>
int main() //统计英文字母和数字字符
{
int n,i;
char ch;
int Num_char=0,Num_Num=0,Num_other=0;
printf("please enter the number of characters:");
scanf("%d",&n);
getchar(); //这里读入并舍弃换行符 使其不参与统计
for(i=0;i<n;i++)
{
ch = getchar();
if(ch>='a' && ch<='z' || ch>='A' && ch<='Z')
{
Num_char++;
}
else if(ch>='0' && ch<='9')
{
Num_Num++;
}
else
{
Num_other++;
}
}
printf("The number of letter is %d\nThe number of Number is %d\nThe number of other is %d",Num_char,Num_Num,Num_other);
return 0;
}
程序运行结果:
正确