C++中atoi处理异常的方法

寻技术 C/C++编程 3小时前 4

在C++中,可以使用try-catch语句来处理atoi函数可能引发的异常。具体的方法如下:

#include <iostream> #include <cstdlib> int main() { const char* str = "123abc"; int result; try { result = std::atoi(str); std::cout << "Converted value: " << result << std::endl; } catch(const std::invalid_argument& e) { std::cerr << "Invalid argument: " << e.what() << std::endl; } catch(const std::out_of_range& e) { std::cerr << "Out of range: " << e.what() << std::endl; } return 0; }

在上面的示例中,我们使用try-catch语句捕获了可能抛出的invalid_argument和out_of_range异常,并在捕获到异常时输出相应的错误信息。这样可以避免程序因为atoi函数的异常而崩溃,提高程序的健壮性。

关闭

用微信“扫一扫”