首页 > 解决方案 > 从键盘读取字符串时出现意外输出

问题描述

这个程序正在返回一些我无法理解的东西。附件是O/P简单程序的截图,用于查找空格数、制表符等。

我错过了什么?

#include <stdio.h>
#include <string.h>

int main() {
    int count[] = { 0, 0, 0 }; /* 0 is spaces, 1 is tabs and 2 for newline. */
    int string;
    
    printf("Enter the paragraph: \n");
    while ((string = getchar()) != EOF) {
        if (string == ' ')
            count[0]++;
        else if (string == '\t')
            count[1]++;
        else if (string == '\n')
            count[2]++;
    }
    printf("There are %d Spaces.\n", count[0]);
    printf("There are %d Tabs.\n", count[1]);
    printf("There are %d Newlines.\n", count[2]);
    return 0;
}

在此处输入图像描述

标签: c

解决方案


从屏幕截图中可以看出,您输入的内容Ctrl-Z是向程序发出文件结束信号。虽然这适用于 MS/DOS 和 Windows 终端等遗留系统,但此组合键在 linux 等 unix 系统上具有不同的含义:它会导致当前进程被其正在运行的 shell 父进程挂起。稍后可以使用该fg命令恢复该过程。

要在此系统上发出文件结束信号,您应该键入Ctrl-D

你的程序应该会产生预期的结果。代码看起来不错,尽管命名string一个intgetchar(). 这样的变量通常被命名为c.


推荐阅读