用getchar输入没问题,但用scanf就不行了,怎么用scanf输入呢?
#include <stdio.h>
int main() {
char c;
int letters=0,space=0,digit=0,other=0;
printf("请输入一行字符:");
scanf("%s",&c);
while (c='\n') {
if (c >= 'a'&&c <= 'z' || c >= 'A'&&c <= 'Z') {
letters++;
} else if (c == ' ') {
space++;
} else if (c >= '0'&&c <= '9') {
digit++;
} else {
other++;
}
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符:%d\n",letters,space,digit,other);
return 0;
}
是因为while循环没结束吗?搞不懂
#include <stdio.h>
int main()
{
char c;
int letters = 0, space = 0, digit = 0, other = 0;
printf("请输入一行字符:");
while (1)
{
scanf("%c",&c);
if(c == '\n') break;
if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z')
{
letters++;
}
else if (c == ' ')
{
space++;
}
else if (c >= '0' && c <= '9')
{
digit++;
}
else
{
other++;
}
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符:%d\n", letters, space, digit, other);
return 0;
}
改成
char c[];
scanf("%s",c);
scanf输入不支持空格统计
#include <stdio.h>
#include <string.h>
int main() {
char c[250];
int letters=0,space=0,digit=0,other=0;
int j=0;
printf("请输入一行字符:");
scanf("%s",c);
while (j<strlen(c))
{
if ((c[j] >= 'a'&&c[j] <= 'z') || (c[j] >= 'A'&&c[j] <= 'Z'))
{
letters++;
} else if (c[j] == ' ') {
space++;
} else if (c[j] >= '0'&&c[j] <= '9') {
digit++;
} else {
other++;
}
j++;
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符:%d\n",letters,space,digit,other);
return 0;
}
建议用gets();输入字符串
如下
#include <stdio.h>
#include <string.h>
int main() {
char c[250];
int letters=0,space=0,digit=0,other=0;
int j=0;
printf("请输入一行字符:");
//scanf("%s",c);
gets(c);
while (j<strlen(c))
{
if ((c[j] >= 'a'&&c[j] <= 'z') || (c[j] >= 'A'&&c[j] <= 'Z'))
{
letters++;
} else if (c[j] == ' ') {
space++;
} else if (c[j] >= '0'&&c[j] <= '9') {
digit++;
} else {
other++;
}
j++;
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符:%d\n",letters,space,digit,other);
return 0;
}
程序整体逻辑正确,有两处错误需要修正:
1、第六行的 scanf接收时 应该使用 %c,接收字符类型,%s是字符串的匹配格式符;
2、第七行的 while 后面的条件 应该是 c=='\n' 来判断,c='\n'是表示赋值,这样就覆盖了刚刚从键盘接收的字符,最后只能累加到 other变量中。
我理解你犯了初学者的几个错误
while (c='\n')
判断用两个=
#include <stdio.h>
int main() {
char c[10000] = {0};
int letters = 0, space = 0, digit = 0, other = 0;
printf("请输入一行字符:");
gets(c)
int i = 0;
while (c[i] != '\0') {
if ((c[i] >= 'a' && c[i] <= 'z') || (c[i] >= 'A' && c[i] <= 'Z')) {
letters++;
}
else if (c[i] == ' ') {
space++;
}
else if (c[i] >= '0' && c[i] <= '9') {
digit++;
}
else {
other++;
}
i++;
}
printf("字母数:%d\n空格数:%d\n数字数:%d\n其他字符:%d\n", letters, space, digit, other);
return 0;
}