信息发布→ 登录 注册 退出

c++中如何进行字符串和数字的相互转换_c++字符串与数值转换方法

发布时间:2025-11-05

点击量:
C++中字符串与数字转换常用方法包括:1. std::to_string将数字转字符串,支持int、double等类型;2. std::stringstream实现双向转换,兼容旧版本;3. stoi、stod等函数将字符串转数值,需用try-catch处理异常。

在C++中,字符串和数字之间的相互转换是常见操作。根据不同需求和C++标准版本,有多种方法可以实现。下面介绍几种常用且实用的转换方式。

1. 使用 std::to_string 进行数字转字符串

将数值类型(如 int、float、double 等)转换为字符串,最简单的方法是使用 std::to_string 函数,它是 C++11 引入的标准库函数。

  • int 转 string:
  • int num = 123;
    std::string str = std::to_string(num);

  • double 转 string:
  • double d = 3.14;
    std::string str = std::to_string(d);

注意:std::to_string 转换浮点数时可能保留较多小数位,需根据需要格式化输出。

2. 使用 stringstream 进行双向转换

std::stringstream 是一种灵活的方式,适用于各种类型与字符串之间的转换,兼容性好,适合旧版本C++。

  • 数字转字符串:
  • int num = 456;
    std::stringstream ss;
    ss << num;
    std::string str = ss.str();

  • 字符串转数字:
  • std::string str = "789";
    int num;
    std::stringstream ss(str);
    ss >> num;

这种方法支持 int、float、double 等多种类型,且可处理带空格或多个数值的字符串。

3. 使用 stoi、stod 等函数进行字符串转数字

C++11 提供了专门用于字符串转数值的函数,简洁高效。

  • string 转 int:std::stoi("123")
  • string 转 long:std::stol("123456")
  • string 转 double:std::stod("3.14")
  • string 转 float:std::stof("2.5f")

这些函数会抛出异常(如 std::invalid_argument 或 std::out_of_range),建议用 try-catch 包裹以增强健壮性。

4. 处理转换异常

当字符串格式不合法时,转换可能失败。例如 stoi 对非数字字符串会抛异常。

示例:

try {
std::string bad_str = "abc";
int num = std::stoi(bad_str);
} catch (const std::invalid_argument& e) {
std::cout << "无效参数: " << e.what() << std::endl;
} catch (const std::out_of_range& e) {
std::cout << "数值超出范围: " << e.what() << std::endl;
}

基本上就这些。选择哪种方法取决于你的编译器支持和具体场景。std::to_string 和 stoi/stod 简洁现代,stringstream 更灵活通用。合理使用这些方法,能轻松完成字符串与数字的互转。

标签:# double  # 可以实现  # 几种  # 较多  # 有多  # 它是  # 适用于  # 多个  # 是一种  # 旧版本  # 转数  # 值类型  # c++  # int  # 字符串  # const  # catch  # try  # Float  # String  # 标准库  # 格式化输出  # stream  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!