命名空间
变体
操作

std::getchar

来自 cppreference.cn
< cpp‎ | io‎ | c
 
 
 
 
定义于头文件 <cstdio>
int getchar();

stdin 读取下一个字符。

等同于 std::getc(stdin)

目录

[编辑] 参数

(无)

[编辑] 返回值

成功时返回获取的字符,失败时返回 EOF

如果失败是由文件结束条件引起的,则额外设置 stdin 上的 eof 指示器(参见 std::feof())。如果失败是由其他错误引起的,则设置 stdin 上的错误指示器(参见 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
^[

[编辑] 参见

从文件流中获取字符
(函数) [编辑]
C 文档 关于 getchar