scanf getchar的区别?

来源:百度知道 编辑:UC知道 时间:2024/05/22 13:26:24
#include<stdio.h>
int main()
{ char c;
int letters=0,nums=0,space=0,others=0;
while((c=getchar())!='\n')
{
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
letters++;
else if(c==' ')
space++;
else if(c>='0'&&c<='9')
nums++;
else
others++;
}
printf("letters=%d space=%d nums=%d others=%d",letters,space,nums,others);
return 0;

}

#include<stdio.h>
int main()
{ char c;
int letters=0,nums=0,space=0,others=0;
scanf("%c",&c);
while(c!='\n')
{
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
letters++;
else if(c==' ')
space++;
else if(c>='0'&&c<='9')
nums++;
else
others++;
}
printf(&

scanf和getchar都是读取输入
第二个程序因为scanf没有再循环里面,只读取一次,所以不能成功
修改成:
#include<stdio.h>
int main()
{ char c;
int letters=0,nums=0,space=0,others=0;

while(scanf("%c",&c),c!='\n')
{
if(c>='a'&&c<='z'||c>='A'&&c<='Z')
letters++;
else if(c==' ')
space++;
else if(c>='0'&&c<='9')
nums++;
else
others++;
}
printf("letters=%d space=%d nums=%d others=%d",letters,space,nums,others);
return 0;

}