getc()、getchar()、getch() 和 getche() 的区别

x33g5p2x  于2021-09-19 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(364)

所有这些函数都从输入中读取一个字符并返回一个整数值。返回整数以容纳用于指示失败的特殊值。EOF值通常用于此目的。

getc()

它从给定的输入流中读取单个字符,并在成功时返回相应的整数值(通常是读取字符的ASCII值)。失败时返回EOF。
    语法:

  1. int getc(FILE *stream);

示例:

  1. // Example for getc() in C
  2. #include <stdio.h>
  3. int main()
  4. {
  5. printf("%c", getc(stdin));
  6. return(0);
  7. }

输出:

  1. Input: g (press enter key)
  2. Output: g
getchar()

getc() 和 getchar() 之间的区别是 getc() 可以从任何输入流读取,但是 getchar() 只能从标准输入流读取。因此 getchar() 等价于 getc(stdin)。
    语法:

  1. int getchar(void);

示例:

  1. // Example for getchar() in C
  2. #include <stdio.h>
  3. int main()
  4. {
  5. printf("%c", getchar());
  6. return 0;
  7. }

输出:

  1. Input: g(press enter key)
  2. Output: g
getch()

getch() 是一个非标准函数,存在于 conio.h 头文件中,该文件主要由 MS-DOS 编译器(如 Turbo C)使用。它不是 C 标准库或 ISO C 的一部分,也不是由 POSIX 定义的。
    与上述函数一样,它也从键盘读取单个字符。 但它不使用任何缓冲区,因此输入的字符会立即返回,无需等待回车键。
    语法:

  1. int getch();

示例:

  1. // Example for getch() in C
  2. #include <stdio.h>
  3. #include <conio.h>
  4. int main()
  5. {
  6. printf("%c", getch());
  7. return 0;
  8. }

输出:

  1. Input: g (Without enter key)
  2. Output: Program terminates immediately.
  3. But when you use DOS shell in Turbo C,
  4. it shows a single g, i.e., 'g'
getche()

与 getch() 一样,这也是conio.h中的一个非标准函数。它从键盘读取单个字符,并立即显示在输出屏幕上,而无需等待回车键。
    语法:

  1. int getche(void);

示例:

  1. #include <stdio.h>
  2. #include <conio.h>
  3. // Example for getche() in C
  4. int main()
  5. {
  6. printf("%c", getche());
  7. return 0;
  8. }

输出:

  1. Input: g(without enter key as it is not buffered)
  2. Output: Program terminates immediately.
  3. But when you use DOS shell in Turbo C,
  4. double g, i.e., 'gg'
参考文档

[1]Vankayala Karunakar.Difference between getc(), getchar(), getch() and getche()[EB/OL].https://www.geeksforgeeks.org/difference-getchar-getch-getc-getche/,2018-12-13.

相关文章