std::getchar
来自cppreference.com
| 在标头 <cstdio> 定义
|
||
| |
||
从 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 文档
| |