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:
- double 转 string:
int num = 123;<br>std::string str = std::to_string(num);
double d = 3.14;<br>std::string str = std::to_string(d);
立即学习“C++免费学习笔记(深入)”;
注意:std::to_string 转换浮点数时可能保留较多小数位,需根据需要格式化输出。
2. 使用 stringstream 进行双向转换
std::stringstream 是一种灵活的方式,适用于各种类型与字符串之间的转换,兼容性好,适合旧版本C++。
- 数字转字符串:
- 字符串转数字:
int num = 456;<br>std::stringstream ss;<br>ss << num;<br>std::string str = ss.str();
std::string str = "789";<br>int num;<br>std::stringstream ss(str);<br>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 {<br> std::string bad_str = "abc";<br> int num = std::stoi(bad_str);<br>} catch (const std::invalid_argument& e) {<br> std::cout << "无效参数: " << e.what() << std::endl;<br>} catch (const std::out_of_range& e) {<br> std::cout << "数值超出范围: " << e.what() << std::endl;<br>}
基本上就这些。选择哪种方法取决于你的编译器支持和具体场景。std::to_string 和 stoi/stod 简洁现代,stringstream 更灵活通用。合理使用这些方法,能轻松完成字符串与数字的互转。