文章目录
- 1.C ++字符串与浮点数和双浮点数转换
- 示例1:C ++字符串转换为浮点和双浮点数
- 示例2:将C ++ char数组转换为double
- 2.C ++浮点和双浮点数转换为字符串
- 示例3:使用to_string()将浮点数和双浮点数转换为字符串
- 示例4:使用stringstream将浮点数和双浮点数转换为字符串
1.C ++字符串与浮点数和双浮点数转换
std :: stof() - 将string转换为float
std :: stod() - 将string转换为double
std :: stold() - 将string转换为long double。
示例1:C ++字符串转换为浮点和双浮点数
#include <iostream>
#include <string>int main() {std::string str = "123.4567";// 将字符串转换为浮点数float num_float = std::stof(str);// 将字符串转换为双浮点数 doubledouble num_double = std::stod(str);std:: cout<< "num_float = " << num_float << std::endl;std:: cout<< "num_double = " << num_double << std::endl;return 0;
}
示例2:将C ++ char数组转换为double
#include <iostream>// atoi()需要cstdlib
#include <cstdlib>int main() {// 声明和初始化字符数组char str[] = "123.4567";double num_double = std::atof(str);std::cout << "num_double = " << num_double << std::endl;return 0;
}
2.C ++浮点和双浮点数转换为字符串
示例3:使用to_string()将浮点数和双浮点数转换为字符串
#include <iostream>
#include <string>int main() {float num_float = 123.4567F;double num_double = 123.4567;std::string str1 = std::to_string(num_float);std::string str2 = std::to_string(num_double);std::cout << "Float 转换为 String = " << str1 << std::endl;std::cout << "Double 转换为 String = " << str2 << std::endl;return 0;
}
示例4:使用stringstream将浮点数和双浮点数转换为字符串
#include <iostream>
#include<string>
#include<sstream> // 使用stringstreamint main() {float num_float = 123.4567F;double num_double = 123.4567;// 创建stringstream对象std::stringstream ss1;std::stringstream ss2;// 将num_float的值分配给ss1ss1 << num_float;// 将num_float的值分配给ss2ss2 << num_double;//用ss1和ss2的值初始化两个字符串变量//然后使用str()函数将其转换为字符串格式std::string str1 = ss1.str();std::string str2 = ss2.str();std::cout << "Float 转换为 String = " << str1 << std::endl;std::cout << "Double 转换为 String = " << str2 << std::endl;return 0;
}