std::getchar

出自cppreference.com
< cpp | io | c
 
 
 
 
在標頭 <cstdio> 定義
int getchar();

stdin 讀取下個字符。

等價於 std::getc(stdin)

參數

(無)

返回值

成功時為獲得的字符,失敗時為 EOF

若因文件尾條件而導致失敗,則另外設置 stdin 上的文件尾指示器(見 feof())。若因某個其他錯誤導致失敗,則設置 stdin 上的錯誤指示器(見 ferror())。

示例

std::getchar with error checking. Exit program by entering ESC char.

#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>

int main()
{
    for (int ch; (ch = std::getchar()) != EOF ;) // 读取/打印来自 stdin 的 "abc"
    {
        if (std::isprint(ch))
            std::cout << static_cast<char>(ch) << '\n';
        if (ch == 27) // 'ESC' (escape) 的 ASCII
            return EXIT_SUCCESS;
    }

    // 测试抵达 EOF。
    if (std::feof(stdin)) // 如果由文件尾条件导致失败
        std::cout << "抵达文件尾\n";
    else if (std::ferror(stdin)) // 如果由某种其他错误导致失败
    {
        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 文檔