C语言 循环语句例题 统计从键盘输入一行字符的个数

#include <stdio.h>
int main()
{
int n=0;
printf("input a string:\n");
while(getchar()!='\n');
{
n++;
}
printf("%d\n", n);
return 0;
}
为什么我输入多少个字符,他都只显示1?

第1个回答  2013-11-26
Because there exits a redundant ";" bebind the satance of "while(getchar()!='\n')",so,when the programe running at this instruction,it will poform this while until you press "\n" ,then the next instruction "n++" will be performed,and it will be "1",thus,whatever you pressed,the result is "1".

Understand?
This is a low-grade problem,I wish you counld not make this mistake again.
第2个回答  2013-11-26
#include "stdio.h"
void main()
{
 char c[100];
 int i;
 scanf("%s",c);
 i=printf("%s",c);
 printf("\n %d chars\n",i);
}

第3个回答  推荐于2017-10-06
1、while(getchar()!='\n')后面多了一个分号,即多了一个空语句,所以后面的{ n++;}并不是while循环内的语句,只被执行了一次,所以n=1。
2、即使while后面没有多分号,最后结果也是1。这是因为getchar()函数只能从键盘接收一个字符,它不能按照你的期望接收一个字符串,所以程序应改为:
#include <stdio.h>
int main()
{
int i=0,n=0;
char *s;
printf("input a string:\n");
gets(s);
while(s[i]!='\n');
{
n++;
i++;
}
printf("%d\n", n);
return 0;
}本回答被提问者采纳
第4个回答  2013-11-26
whle那行多了个分好

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网