getchar 函数在读取输入时可能会遇到异常情况,例如输入流关闭、输入错误等。为了处理这些异常,可以使用 try-catch 语句(C++)或 try-except 语句(Python)。
下面是使用 C++ 处理 getchar 输入异常的示例:
#include <iostream>
#include <limits>
int main() {
int ch;
std::cout << "请输入一个字符: ";
try {
ch = getchar();
if (ch == EOF) {
throw std::runtime_error("输入流关闭");
}
std::cout << "你输入的字符是: " << ch << std::endl;
} catch (const std::runtime_error& e) {
std::cerr << "发生异常: " << e.what() << std::endl;
}
return 0;
}
在这个示例中,我们使用 try 块包裹 getchar() 函数调用。如果 getchar() 返回 EOF,我们抛出一个 std::runtime_error 异常。在 catch 块中,我们捕获这个异常并输出异常信息。
下面是使用 Python 处理 getchar 输入异常的示例:
try:
ch = input("请输入一个字符: ")
if ch == "":
raise EOFError("输入流关闭")
print(f"你输入的字符是: {ch}")
except EOFError as e:
print(f"发生异常: {e}")
在这个示例中,我们同样使用 try 块包裹 input() 函数调用。如果用户直接按下回车键,input() 函数将返回空字符串。我们抛出一个 EOFError 异常并在 except 块中捕获它。