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

#include<stdio.h>intmain(){intn=0;printf("inputastring:\n");while(getchar()!='\n');{n... #include <stdio.h>
int main()
{
int n=0;
printf("input a string:\n");
while(getchar()!='\n');
{
n++;
}
printf("%d\n", n);
return 0;
}
为什么我输入多少个字符,他都只显示1?
展开
 我来答
baby爱你一兆年
2013-11-26
知道答主
回答量:18
采纳率:0%
帮助的人:11.1万
展开全部
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.
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
wind556
2013-11-26 · TA获得超过250个赞
知道小有建树答主
回答量:673
采纳率:50%
帮助的人:262万
展开全部
#include "stdio.h"
void main()
{
 char c[100];
 int i;
 scanf("%s",c);
 i=printf("%s",c);
 printf("\n %d chars\n",i);
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
百度网友e88eac6
推荐于2017-10-06 · TA获得超过2274个赞
知道小有建树答主
回答量:413
采纳率:73%
帮助的人:191万
展开全部
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;
}
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
ab52525258
2013-11-26 · TA获得超过167个赞
知道小有建树答主
回答量:275
采纳率:0%
帮助的人:173万
展开全部
whle那行多了个分好
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 2条折叠回答
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式