如何在 C++ 中把 Char 数组转换为 Int

本文将介绍将 char 数组转换为 int 类型的 C++ 方法。

使用 std::strtol 函数将 char 数组转换为 int 类型

strtol 方法将 char 数组中的第一个有效字符解释为整数类型。该函数将转换后的整数的数基作为第三个参数,其值在-{0,2,3,…,36}范围内。第二个参数是类型为 char **endptr 的参数,它是可选的,如果传递了该参数,则存储指向最后一个字符解释后的字符的地址。

#include <iostream>#include <string>using std::cout; using std::endl;
using std::cin; using std::string;
int main() {
    string str1("23323experimental_string");
    auto str1_n = std::strtol(str1.data(), nullptr, 10);
    printf("%ld", str1_n);
    return EXIT_SUCCESS;
}

输出:

23323

下面的例子演示了 strtol 函数,第二个参数是非 nullptr。请注意,我们只是将 printf 函数作为类型验证工具,在其他情况下应该使用 cout。同样重要的是为 strtol 函数实现错误处理例程,详情可参见这里。

#include <iostream>#include <string>using std::cout; using std::endl;
using std::cin; using std::string;
int main() {
    string str1("23323experimental_string");
    char *char_part = nullptr;
    auto str1_n = std::strtol(str1.data(), &char_part, 10);
    printf("%ld\n", str1_n);
    printf("%s\n", char_part);;
    return EXIT_SUCCESS;
}

输出:

23323
experimental_string

使用 sscanf() 函数将 Char 数组转换为 Int 数组

sscanf 函数从字符串缓冲区读取输入,并根据作为第二个参数传递的格式指定器进行解释。数字值存储在指向 int 变量的指针处。在 sscanf 手册 page中详细介绍了格式指定符。

#include <iostream>#include <string>using std::cout; using std::endl;
using std::cin; using std::string;
int main() {
    string str1("23323experimental_string");
    int str1_n;
    sscanf(str1.data(), "%d", &str1_n);
    printf("%d\n", str1_n);
    return EXIT_SUCCESS;
}

输出:

23323

我们也可以重新实施上面的例子来存储输入字符串的非数字部分。在这种情况下,我们在第二个参数中添加%s 格式说明符,并将目标 char 指针作为第四个参数。请注意,sscanf 是一个可变参数函数,因为它可以从调用者那里接受不同数量的参数。

#include <iostream>#include <string>using std::cout; using std::endl;
using std::cin; using std::string;
int main() {
    string str1("23323experimental_string");
    int str1_n3;
    string str2 {};
    sscanf(str1.data(), "%d%s", &str1_n3, str2.data());
    printf("%d\n", str1_n3);
    printf("%s\n", str2.data());
    return EXIT_SUCCESS;
}

输出:

23323
experimental_string