C++ 字符串转浮点数和双精度数转换
使用这些C++11函数将字符串转换为浮点数的最简单方法是:
- std::stof() - 将
string
转换为float
- std::stod() - 将
string
转换为double
- std::stold() - 将
string
转换为long double
。
这些函数定义在string
头文件中。
示例 1:C++ 字符串转浮点数和双精度数
#include <iostream>
#include <string>
int main() {
std::string str = "123.4567";
// convert string to float
float num_float = std::stof(str);
// convert string to double
double num_double = std::stod(str);
std:: cout<< "num_float = " << num_float << std::endl;
std:: cout<< "num_double = " << num_double << std::endl;
return 0;
}
输出
num_float = 123.457 num_double = 123.457
示例 2:C++ 字符数组转双精度数
我们可以使用std::atof()
函数将char
数组转换为double
。
#include <iostream>
// cstdlib is needed for atoi()
#include <cstdlib>
int main() {
// declaring and initializing character array
char str[] = "123.4567";
double num_double = std::atof(str);
std::cout << "num_double = " << num_double << std::endl;
return 0;
}
输出
num_double = 123.457
C++ 浮点数和双精度数转字符串转换
我们可以使用C++11的std::to_string()
函数将float
和double
转换为string
。对于较旧的C++编译器,我们可以使用std::stringstream
对象。
示例 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 to String = " << str1 << std::endl;
std::cout << "Double to String = " << str2 << std::endl;
return 0;
}
输出
Float to String = 123.456703 Double to String = 123.456700
示例 4:使用 stringstream 将浮点数和双精度数转换为字符串
#include <iostream>
#include<string>
#include<sstream> // for using stringstream
int main() {
float num_float = 123.4567F;
double num_double = 123.4567;
// creating stringstream objects
std::stringstream ss1;
std::stringstream ss2;
// assigning the value of num_float to ss1
ss1 << num_float;
// assigning the value of num_float to ss2
ss2 << num_double;
// initializing two string variables with the values of ss1 and ss2
// and converting it to string format with str() function
std::string str1 = ss1.str();
std::string str2 = ss2.str();
std::cout << "Float to String = " << str1 << std::endl;
std::cout << "Double to String = " << str2 << std::endl;
return 0;
}
输出
Float to String = 123.457 Double to String = 123.457
推荐阅读: C++ 字符串转整数。