名前空間
変種
操作

std::getchar

From cppreference.com
< cpp‎ | io‎ | c
 
 
 
C形式I/O
型とオブジェクト
関数
ファイルアクセス
直接入出力
非書式化入出力
書式付き入力
(C++11)(C++11)(C++11)    
(C++11)(C++11)(C++11)    
書式付き出力
ファイルポジショニング
エラーハンドリング
ファイル操作
 
ヘッダ<cstdio>で定義
int getchar();

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

std::getc(stdin)と同等です。

目次

[編集] パラメータ

(なし)

[編集] 戻り値

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

失敗がファイルの終端条件によって引き起こされた場合、 additionally は stdineof インジケータ(std::feof() 参照)を設定します。失敗がその他のエラーによって引き起こされた場合、 stdinerror インジケータ(std::ferror() 参照)を設定します。

[編集]

エラーチェック付きの `std::getchar`。ESC文字を入力してプログラムを終了します。

#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>
 
int main()
{
    for (int ch; (ch = std::getchar()) != EOF ;) // read/print "abc" from stdin
    {
        if (std::isprint(ch))
            std::cout << static_cast<char>(ch) << '\n';
        if (ch == 27) // 'ESC' (escape) in ASCII
            return EXIT_SUCCESS;
    }
 
    // Test reason for reaching EOF.
    if (std::feof(stdin)) // if failure caused by end-of-file condition
        std::cout << "End of file reached\n";
    else if (std::ferror(stdin)) // if failure caused by some other error
    {
        std::perror("getchar()");
        std::cerr << "getchar() failed in file " << std::quoted(__FILE__)
                  << " at line # " << __LINE__ - 14 << '\n';
        std::exit(EXIT_FAILURE);
    }
 
    return EXIT_SUCCESS;
}

実行結果の例

abc
a
b
c
^[

[編集] 関連項目

ファイルストリームから1文字取得する
(関数) [編集]
English 日本語 中文(简体) 中文(繁體)