getchar与循环

getchar与循环

题目

统计用户输入
从键盘读取用户输入直到遇到#字符,编写程序统计读取的空格数目、读取的换行符数目以及读取的所有其他字符数目。(要求用getchar()输入字符)

程序运行结果示例1:
Please input a string end by #:
abc def↙
jklm op↙
zkm #↙
space: 3,newline: 2,others: 15

程序运行结果示例2:
Please input a string end by #:
hello friend!#↙
space: 1,newline: 0,others: 12

输入格式: getchar()
输出格式:
输入提示信息:”Please input a string end by #:\n”
输出格式:”space: %d,newline: %d,others: %d\n”

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>

int main()
{
int space=0,newline=0,other=0;
char content;
printf("Please input a string end by #:\n");
while((content=getchar())!='#'){
if(content==' '){
space++;
}
else if(content=='\n'){
newline++;
}
else{
other++;
}
}
printf("space: %d,newline: %d,others: %d\n",space,newline,other);
return 0;
}

备注

1.为什么要把content=getchar()整个括起来

= 是赋值运算符,优先级低于 !=

2.为什么不能在while 条件中直接定义(如 while (char content = getchar() != '#')

不符合 C 语言语法规范

3.getchar每次只读取一个字符?

是的,getchar() 函数每次仅读取一个字符

它的工作机制是从标准输入(通常是键盘)中读取一个字符,包括空格、换行符等所有可输入的字符,每次调用只处理一个字符。这也是我们在统计空格、换行符和其他字符时,能通过循环多次调用 getchar() 来逐个字符判断的原因。


getchar与循环
http://example.com/2025/11/14/getchar与循环/
作者
王柏森
发布于
2025年11月14日
许可协议