【问题标题】:C - How do I make this null statement work?C - 我如何使这个空语句起作用?
【发布时间】:2021-01-17 12:09:20
【问题描述】:

我正在关注“The C Programming Language. 2nd Edition”,并且已经达到“1.5.2 Character Counting”。

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

#include <stdio.h>

main() {
    double nc;
    for(nc = 0; getchar() != EOF; ++nc)
        ;
    printf("%.0f\n", nc);
}

然而程序并没有输出输入的字符数:

input
input

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

#include <stdio.h>

main() {
    double nc;
    for (nc = 0; getchar() != EOF; ++nc) {
        printf("%.0f\n", nc);
    }
}

...它提供了正确的输出:

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

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

【问题讨论】:

  • 您需要输入&lt;Enter&gt;&lt;Ctrl+D&gt; (Un*x) 或&lt;Enter&gt;&lt;Ctrl+Z&gt; (Windows) 以向程序发出输入结束信号 (EOF),否则它会“卡在”@ 987654328@.

标签: c null character charactercount


【解决方案1】:

您的代码中有很多问题,但没有一个与空语句有关:

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

检查EOF 新行。

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

https://godbolt.org/z/Yc1c3K

【讨论】:

  • 这在编译器资源管理器中有效,但在我在 Visual Studio 上运行时无效 - 如果我键入内容并按 Enter,它只会关闭窗口,并说它已以“代码 0”退出。
  • 在打印后添加while(1);
  • 效果一样好。您根本看不到它,因为控制台窗口在程序退出后立即关闭。窗户的喜悦。但是您需要尝试自己解决。如果不这样做,您将永远无法学会如何解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多