非常教程

C参考手册

文件输入/输出 | File input/output

getchar

Defined in header <stdio.h>

int getchar(void);

从中读取下一个字符stdin

相当于getc(stdin)

参数

(none).

返回值

获得成功或EOF失败的性格。

如果故障是由文件结束条件引起的,则另外设置eof指示器(参见feof()stdin。如果故障是由其他错误引起的,请设置错误指示器(参见ferror()stdin

带错误检查的getchar。

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{ 
    int ch;
    while ((ch=getchar()) != EOF)   /* read/print "abcde" from stdin */
          printf("%c", ch);
 
    /* Test reason for reaching EOF. */
    if (feof(stdin))          /* if failure caused by end-of-file condition */
       puts("End of file reached");
    else if (ferror(stdin))   /* if failure caused by some other error      */
         {
            perror("getchar()");
            fprintf(stderr,"getchar() failed in file %s at line # %d\n", __FILE__,__LINE__-9);
            exit(EXIT_FAILURE);
         }
 
    return EXIT_SUCCESS;
}

输出:

abcde
End of file reached

参考

  • C11标准(ISO / IEC 9899:2011):
    • 7.21.7.6 getchar函数(p:332)
  • C99标准(ISO / IEC 9899:1999):
    • 7.19.7.6 getchar函数(p:298)
  • C89 / C90标准(ISO / IEC 9899:1990):
    • 4.9.7.6 getchar函数
C

C 语言是一门通用计算机编程语言,应用广泛。C 语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。