📌  相关文章
📜  如何在 C++ 中将字符串转换为整数(1)

📅  最后修改于: 2023-12-03 14:52:15.243000             🧑  作者: Mango

如何在 C++ 中将字符串转换为整数

将字符串转换为整数是开发中常见的需求。在 C++ 中,我们可以使用 stoi() 函数来完成这个转换过程。

stoi() 函数

stoi() 函数定义在 头文件中,可以将一个字符串转换为整数。

int stoi(const string& str, size_t* idx = 0, int base = 10);

函数参数:

  • str:需要被转换的字符串。
  • idx:如果转换过程中出现非数字字符,idx 存储了首个无法被转换的字符的位置。
  • base:字符串所使用的进制数。

函数返回转换后的整数值。

示例代码:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "1234";
    int num = stoi(str);
    cout << num << endl;
    return 0;
}

输出结果:

1234
异常处理

在 stoi() 函数中,如果出现非数字字符,会抛出一个 std::invalid_argument 异常,表示参数错误。如果转换后的整数超出了 int 的范围,会抛出一个 std::out_of_range 异常,表示越界错误。

为了避免这种情况,我们可以使用异常处理机制,捕获这些异常并进行处理。

示例代码:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string str = "123a";

    try
    {
        int num = stoi(str);
        cout << num << endl;
    }
    catch (const invalid_argument& e)
    {
        cout << "Invalid argument: " << e.what() << endl;
    }
    catch (const out_of_range& e)
    {
        cout << "Out of range: " << e.what() << endl;
    }

    return 0;
}

输出结果:

Invalid argument: stoi
结论

对于将字符串转换为整数的需求,我们可以使用 C++ 标准库中的 stoi() 函数进行完成。同时,在使用该函数时,为了避免出现异常,我们需要使用 try-catch 语句对异常进行处理。