【问题标题】:Count number of blanks, spaces, and tabs in C [duplicate]计算C中的空格、空格和制表符的数量[重复]
【发布时间】:2026-01-26 15:50:01
【问题描述】:

我现在正在做 K&R 的练习,我正在使用 C 语言计算空格、空格和制表符的数量。我已经构建了以下代码:

#include <stdio.h>
#include <stdlib.h>

/*Write a program that counts blanks, tabs, and newlines*/

int main()
{
    int c, numblanks, numtabs, numnewlines;

    numblanks = 0;
    numtabs = 0;
    numnewlines = 0;

    printf("Enter some text and press \"Enter\"\n");

    while ((c = getchar()) != EOF) {
        if (c == ' ')
            ++numblanks;
        if (c == '\t')
            ++numtabs;
        if (c == '\n')
            ++numnewlines;
    }

    printf("The total number of blanks is %i\n", numblanks);
    printf("The total number of tabs is %i\n", numtabs);
    printf("The total number of new lines is %i\n", numnewlines);
}

我正在使用 Codeblocks 和在 Windows 10 操作系统上安装的内置 GCC 编译器。当我运行程序时,我在弹出的程序窗口中输入一些文本,然后按“Enter”,没有任何反应。我不确定为什么。我想知道是否有人可以帮助我再看看我的代码,看看我是否遗漏了什么。这是我运行程序时发生的情况的图像:

Program window with typed text, but no reaction

【问题讨论】:

  • 哦,这就是我要找的东西,只是不完全知道如何正确地说出来(即这里的菜鸟......哈哈)。谢谢芽! Ctrl + Z 成功了!
  • 还要注意CTRL+Z does not generate EOF in Windows 10,除非您选中了正确的框。

标签: c gcc codeblocks kernighan-and-ritchie


【解决方案1】:

我没有尝试过您的解决方案,但有时会在程序完成、终端关闭时发生这种情况。尝试在程序末尾添加一个 getchar。

printf("Enter key to exit");
getchar();

这可以在输入字符串后提供帮助(但有时需要使用getchar() 创建循环并检查此函数的结果)

【讨论】: