std::getchar
來自 cppreference.com
定義於標頭檔案 <cstdio> |
||
int getchar(); |
||
從 stdin 讀取下一個字元。
等價於 std::getc(stdin)。
目錄 |
[編輯] 引數
(無)
[編輯] 返回值
成功時返回獲得的字元,失敗時返回 EOF。
如果失敗是由檔案結束條件引起的,還會設定 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 ^[
[編輯] 參閱
從檔案流中獲取一個字元 (函式) | |
有關 getchar 的C 文件
|