经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C 语言 » 查看文章
getc()、getchar()、getch() 和 getche() 的区别
来源:cnblogs  作者:逆行伐仙  时间:2023/10/16 16:06:33  对本文有异议

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

getc()

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

  1. int getc(FILE *stream);
  • 1

????示例:

  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

????示例:

  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
  • 1
  • 2
getch()

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

  1. int getch();
  • 1

????示例:

  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'
  • 1
  • 2
  • 3
  • 4
getche()

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

  1. int getche(void);
  • 1

????示例:

  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'

原文链接:https://www.cnblogs.com/wenyutao1/p/17767514.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号