C++ 字符串与浮点数/双精度数之间的转换以及反向转换

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++11std::to_string()函数将floatdouble转换为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++ 字符串转整数

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战