c - 关于 getchar() 用法的简单问题?

标签 c getchar

在这个非常棒的网站上搜索有关 getchar() 函数的所有内容时,我发现了这篇文章:Why doesn't getchar() wait for me to press enter after scanf()?

#include <stdio.h>

int main()
{
    int value;
    printf("1. option 1.\n2. option 2.\n3. option 3.\n4. Exit\n\nMake an option: ");
    scanf("%d", &value);
    switch (value)
    {
        case 1:
            printf("you selected the option 1.");
            break;
        case 2:
            printf("you selected the option 2.");
            break;
        case 3:
            printf("you selected the option 3.");
            break;
        case 4:
            printf("goodbye");
            break;
        default:
            printf("thats not an option");
            break;
    }
    getchar();//here is the question,why it's useful ?
    return 0;
}

我了解整个程序,并且我了解每次调用它时,getchar 都会从文本流中读取下一个输入字符并将其作为其值返回。也就是说,经过

c = getchar();

变量 c 包含输入的下一个字符。字符通常来自 键盘。

但问题来了:为什么程序员要在程序结束时调用getchar()?

最佳答案

这种做法特别适用于控制台应用程序,这样您就可以强制程序在您按下某个键之前不会停止,以便您可以读取输出。通常在程序执行结束时控制台关闭

关于c - 关于 getchar() 用法的简单问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7375045/

相关文章:

c - 以十六进制打印 : program adds additional 0xFFs

c - getchar() 在用户写入时

c - getchar() != EOF

c - 用 C 中的字符串替换整数

c - 如何在循环中实例化新的结构实例

c - 将整数值输入到 C 中的数组中

c - 库函数返回的变量的内存分配位置

c++ - 从内存缓冲区创建一个 fstream 对象

c - 为什么我在 Raspberry-Pi Jessie Lite 上启动时无法访问标准输入?

C: 使用 "scanf"读取一行其他字符中的 float