C -我如何使这个空语句工作?



我正在学习《C程序设计语言第二版》,并且已经学习了《1.5.2字符计数》

为使用null语句的字符计数器提供的代码如下:

#include <stdio.h>
main() {
double nc;
for(nc = 0; getchar() != EOF; ++nc)
;
printf("%.0fn", nc);
}

但是程序不输出输入的字符数:

input
input

然而,如果我包含大括号并忽略空语句:

#include <stdio.h>
main() {
double nc;
for (nc = 0; getchar() != EOF; ++nc) {
printf("%.0fn", nc);
}
}

…它提供了正确的输出:

input
0
1
2
3
4
5
input
6
7
8
9
10
11

如何使程序的空语句版本工作?

您的代码中有很多问题,但它们都与空语句无关:

  1. main类型和参数错误
  2. 按ENTER键不能关闭stdin,函数不会返回EOF。

检查EOF新行。

int main(void) {
int nc,ch;
for(nc = 0; (ch = getchar()) != EOF && ch != 'n'; ++nc)
;
printf("%dn", nc);
}

https://godbolt.org/z/Yc1c3K

最新更新