C++ String(字符串)和 float/double (浮点数)互转

发布于:2024-12-18 ⋅ 阅读:(106) ⋅ 点赞:(0)

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);

    // 将字符串转换为双浮点数 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;
}
示例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> // 使用stringstream

int main() {
    float num_float = 123.4567F;
    double num_double = 123.4567;
  
    // 创建stringstream对象
    std::stringstream ss1;
    std::stringstream ss2;
  
    // 将num_float的值分配给ss1
    ss1 << num_float;
  
    // 将num_float的值分配给ss2
    ss2 << 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;
}

网站公告

今日签到

点亮在社区的每一天
去签到