求C++中捕获输入数据类型错误的简单示例(类似Python实现)
C++ 输入错误类型时的异常处理实现
下面是两种符合需求的实现方案,效果和你提供的Python示例一致:
方案1:手动检查输入并抛出异常
这种方式逻辑直观,容易理解:
#include <iostream> #include <stdexcept> #include <limits> int main() { try { double x; std::cout << "Input a real number:"; // 尝试读取浮点数,失败则处理 if (!(std::cin >> x)) { // 重置流的错误状态 std::cin.clear(); // 清空缓冲区里的无效输入 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 抛出自定义异常 throw std::invalid_argument("Error in data type!, need to be a real number, not char "); } std::cout << "Your input: " << x << std::endl; } catch (const std::invalid_argument& e) { std::cerr << e.what() << std::endl; } return 0; }
方案2:配置输入流自动抛出异常
通过设置流的异常掩码,让输入流在读取失败时自动抛出标准异常:
#include <iostream> #include <stdexcept> #include <limits> int main() { try { double x; std::cout << "Input a real number:"; // 配置流在读取失败(failbit)或出错(badbit)时抛出异常 std::cin.exceptions(std::ios::failbit | std::ios::badbit); std::cin >> x; std::cout << "Your input: " << x << std::endl; } catch (const std::ios_base::failure&) { // 重置流状态并清空无效输入 std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cerr << "Error in data type!, need to be a real number, not char " << std::endl; } return 0; }
重要提示:
- 两种方案中,
cin.clear()都是必须的——它会重置输入流的错误标志位,不然后续所有输入操作都会直接失败。 cin.ignore(...)用来清除缓冲区里残留的无效输入内容,避免这些垃圾数据影响下一次输入操作。- 方案1更贴近你Python示例的异常逻辑,手动抛出指定类型的异常;方案2则利用C标准库的流异常机制,更符合C的原生处理方式。
内容的提问来源于stack exchange,提问作者focaazul
相关产品推荐
相关产品推荐

