c++中int、float、double类型数据与string类型数据相互转换
1、string->int
#include <iostream>
#include <string>
int main() {
std::string str = "123";
int num = std::stoi(str);
std::cout << "转换后的整数: " << num << std::endl;
return 0;
}
stoi 函数位于 string头文件中,使用时需要包含该头文件 。如果字符串不能被正确转换为整数(比如包含非数字字符), stoi 函数会抛出 std::invalid_argument 或 std::out_of_range 异常。
2、string->float
在 C++ 中,可使用 std::stof 函数将 std::string 类型转换为 float 类型, std::stof 函数定义在 头文件中,用于从字符串中提取 float 类型的值。以下是示例代码:
#include <iostream>
#include <string>
int main() {
std::string str = "3.14";
float num = std::stof(str);
std::cout << "转换后的 float 类型值为: " << num << std::endl;
return 0;
}
若字符串格式不符合 float 类型的要求,会抛出 std::invalid_argument 异常;若转换后的值超出 float 类型的表示范围,则会抛出 std::out_of_range 异常。
3、string->double
在 C++ 中,可以使用 std::stod 函数将 std::string 类型转换为 double 类型, std::stod 是 头文件中提供的标准库函数,用于将字符串转换为双精度浮点数。示例代码如下:
#include <iostream>
#include <string>
int main() {
std::string str = "3.14159";
double num = std::stod(str);
std::cout << "转换后的 double 类型值为: " << num << std::endl;
return 0;
}
如果字符串格式不正确,无法进行有效的转换,该函数会抛出 std::invalid_argument 或 std::out_of_range 异常(取决于具体情况)。
4、在 C++ 中将 int, float, double 转换为 string
在 C++ 中有几种方法可以将数值类型(int, float, double)转换为字符串(string)。以下是常用的几种方法:
(1). 使用 std::to_string (C++11 及以上)
#include <string>
int main() {
int i = 42;
float f = 3.14f;
double d = 2.71828;
std::string s1 = std::to_string(i); // int 转 string
std::string s2 = std::to_string(f); // float 转 string
std::string s3 = std::to_string(d); // double 转 string
return 0;
}
(2). 使用 std::stringstream
#include <sstream>
#include <string>
int main() {
int i = 42;
float f = 3.14f;
double d = 2.71828;
std::stringstream ss;
// int 转 string
ss << i;
std::string s1 = ss.str();
ss.str(""); // 清空流
// float 转 string
ss << f;
std::string s2 = ss.str();
ss.str("");
// double 转 string
ss << d;
std::string s3 = ss.str();
return 0;
}
(3). 使用 sprintf (C风格,需要包含)
#include <cstdio>
#include <string>
int main() {
int i = 42;
float f = 3.14f;
double d = 2.71828;
char buffer[50];
// int 转 string
sprintf(buffer, "%d", i);
std::string s1(buffer);
// float 转 string
sprintf(buffer, "%f", f);
std::string s2(buffer);
// double 转 string
sprintf(buffer, "%lf", d);
std::string s3(buffer);
return 0;
}
(4). 使用 fmt 库 (C++20 的 std::format 的前身)
#include <fmt/core.h>
int main() {
int i = 42;
float f = 3.14f;
double d = 2.71828;
std::string s1 = fmt::format("{}", i);
std::string s2 = fmt::format("{}", f);
std::string s3 = fmt::format("{}", d);
return 0;
}
注意事项
std::to_string
是最简单的方法,但在某些编译器上可能对浮点数的格式化不够灵活std::stringstream
提供了最大的灵活性,可以控制格式(如精度、科学计数法等)- C++20 引入了
std::format
,它提供了类似 Python 的字符串格式化功能,但目前并非所有编译器都完全支持
对于浮点数,如果需要控制精度,可以使用 stringstream 或 format:
#include <sstream>
#include <iomanip>
float f = 3.1415926f;
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << f; // 保留两位小数
std::string s = ss.str(); // "3.14"