名前空間
変種
操作

getchar

提供: cppreference.com
< c‎ | io
 
 
ファイル入出力
型とオブジェクト
関数
ファイルアクセス
直接入出力
書式なし入出力
getchar
(C11未満)(C11以上)
(C95)(C95)
(C95)
(C95)(C95)
(C95)
(C95)
書式付き入力
 
ヘッダ <stdio.h> で定義
int getchar(void);

stdin から次の文字を読み込みます。

getc(stdin) と同等です。

目次

[編集] 引数

(なし)

[編集] 戻り値

成功した場合は取得した文字、失敗した場合は EOF

失敗がファイル終端に達したことに起因する場合、さらに stdinファイル終端指示子 (feof() を参照) をセットします。 失敗が何らかの他のエラーに起因する場合、 stdinエラー指示子 (ferror() を参照) をセットします。

[編集]

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 standard (ISO/IEC 9899:2011):
  • 7.21.7.6 The getchar function (p: 332)
  • C99 standard (ISO/IEC 9899:1999):
  • 7.19.7.6 The getchar function (p: 298)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 4.9.7.6 The getchar function

[編集] 関連項目

ファイルストリームから文字を取得します
(関数) [edit]