【问题标题】:Why are we using getchar() in while loop to receive values and getch or getche function cannot be used?为什么我们在 while 循环中使用 getchar() 来接收值而不能使用 getch 或 getche 函数?
【发布时间】:2020-09-13 08:32:53
【问题描述】:

为什么我们在while循环中使用getchar()函数在写模式中接收值,为什么getch或getche函数不能用过吗?

#include<stdio.h>
#include<conio.h>
main()
{
    clrscr();
    FILE *f;
    char r;
    f=fopen("muster_up.txt","w");
    while((r=getchar())!=EOF)
    {
        fputc(r,f);
    }
    fclose(f);
    f=fopen("muster_up.txt","r");
    while((r=fgetc(f))!=EOF)
    {
        printf("%c",r);
    }
    fclose(f);
    getch();
}

【问题讨论】:

    标签: c


    【解决方案1】:

    getchar 是标准的 c 函数,在 stdio.h 中, getch, getche 是非标准函数,用于旧的 Windows/MS-DOS 系统,它们在 conio.h 中

    getch 和 getche 都不会等待用户按回车,而是立即读入字符。 getch 也不会回显字符,但 getche 会。

    它是这样工作的:getchar 被调用,stdio 输入缓冲区是空的,所以它等待用户输入。用户键入一串字符(一个句子),按回车键,这些字符被存储在输入缓冲区中,然后 getchar 从中获取第一个字符。由于我们在循环中调用它,它会从输入缓冲区中读取所有字符,直到它为空,然后等待。

    尝试使用 getch:如果您不立即输入字符,程序将退出。此外,getchar 为用户输入提供了更大的灵活性。

    getchar,上述函数从键盘获取输入。

    【讨论】:

      猜你喜欢
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 2020-08-22
      • 2019-01-27
      • 1970-01-01
      • 2011-04-21
      相关资源
      最近更新 更多