17370845950

c++怎么将string类型转换为int类型_c++字符串转整数的常用方法与示例
C++中string转int常用方法包括:①stoi()(推荐,简洁但需异常处理);②stringstream(灵活可检测错误);③atoi()(C风格,失败返回0无提示);④from_chars(C++17+,高效无异常)。日常推荐stoi(),性能敏感用from_chars。

在C++中,将string类型转换为int类型是常见的操作。有多种方法可以实现这一目标,每种方式适用于不同的场景。下面介绍几种常用且可靠的方法,并附上示例代码。

使用 stoi() 函数(推荐)

stoi() 是 C++11 引入的字符串转整数函数,定义在

 头文件中,使用简单直观。

语法:
int std::stoi(const std::string& str)

示例:

#include 
#include 
using namespace std;

int main() {
    string str = "12345";
    int num = stoi(str);
    cout << "转换结果:" << num << endl;  // 输出:12345
    return 0;
}

注意:如果字符串包含非法字符或超出整数范围,stoi() 会抛出异常(如 invalid_argumentout_of_range),建议用 try-catch 捕获。

使用 stringstream 类

stringstream 提供了一种更灵活的类型转换方式,适合需要同时处理多种数据类型的场景。

示例:

#include 
#include 
#include 
using namespace std;

int main() {
    string str = "6789";
    int num;
    stringstream ss(str);
    ss >> num;
    
    if (ss.fail()) {
        cout << "转换失败" << endl;
    } else {
        cout << "转换结果:" << num << endl;
    }
    return 0;
}

优点是能检测转换是否成功,缺点是代码稍显冗长。

使用 atoi() 函数(C风格)

atoi() 来自 C 标准库,需包含 头文件。它接受 C 风格字符串(const char*)。

示例:

#include 
#include 
#include 
using namespace std;

int main() {
    string str = "42";
    int num = atoi(str.c_str());
    cout << "转换结果:" << num << endl;
    return 0;
}

注意:atoi() 在转换失败时返回 0,无法区分“转换失败”和“原字符串就是0”,因此不推荐用于需要错误处理的场合。

使用 from_chars(C++17 起,高效无异常)

如果你使用的是 C++17 或更高版本,std::from_chars 是一种更高效、无异常的方式,适合性能敏感场景。

示例:

#include 
#include 
#include 
#include 
using namespace std;

int main() {
    string str = "54321";
    int num;
    auto [ptr, ec] = from_chars(str.data(), str.data() + str.size(), num);

    if (ec == errc()) {
        cout << "转换成功:" << num << endl;
    } else {
        cout << "转换失败" << endl;
    }
    return 0;
}

该方法不会抛出异常,通过返回值判断是否成功,适合高可靠性系统。

基本上就这些常用方法。日常开发中,推荐优先使用 stoi(),代码简洁且易读;若需更强健的错误处理,可结合 try-catch 使用。对于老项目或兼容C代码,atoi() 也可用,但要注意其局限性。高性能场景建议尝试 from_chars。选择合适的方法,能让字符串转整数更安全高效。