温馨提示×

C++ stoi函数如何处理异常

c++
小樊
90
2024-06-26 10:47:44
栏目: 编程语言

C++中的stoi函数用于将字符串转换为整数。当转换过程中出现异常时,stoi函数会抛出invalid_argument异常。这种异常表示输入字符串无效,无法进行转换。

例如,如果我们尝试将一个非数字的字符串转换为整数,stoi函数会抛出invalid_argument异常。以下是一个示例代码:

#include <iostream>
#include <string>

int main() {
    try {
        std::string s = "hello";
        int num = std::stoi(s);
        std::cout << "Converted number: " << num << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cerr << "Invalid argument: " << e.what() << std::endl;
    }
    
    return 0;
}

在上面的示例中,我们尝试将字符串"hello"转换为整数。由于该字符串不是一个有效的整数表示,stoi函数会抛出invalid_argument异常,并在catch块中捕获异常并输出错误消息。

0