std::getchar
From cppreference.com
| ヘッダ <cstdio>で定義 |
||
| int getchar(); |
||
stdinから次の文字を読み取ります。
std::getc(stdin)と同等です。
目次 |
[編集] パラメータ
(なし)
[編集] 戻り値
成功した場合は取得された文字、失敗した場合は EOF。
失敗がファイルの終端条件によって引き起こされた場合、 additionally は stdin の eof インジケータ(std::feof() 参照)を設定します。失敗がその他のエラーによって引き起こされた場合、 stdin の error インジケータ(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文字取得する (関数) | |
| Cドキュメント getchar
| |