c++ string double 互转

string str =  "123456"
double    dblValue   =   _atof(str);


C++通过ostringstream实现任意类型转string

2010年9月23日代码疯子

再使用整型转string的时候感觉有点棘手,因为itoa不是标准C里面的,而且即便是有itoa,其他类型转string不是很方便。后来去网上找了一下,发现有一个好方法:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
 int a = 55;
 double b = 65.123;
 string str = "";

 //头文件是sstream
 ostringstream oss;
 oss << a << "---" << b;

 str = oss.str();
 cout << str << endl;
 return 0;
}
输出就是55—65.123,怎么样,转换起来非常的自由。就和输出到屏幕一样。


Copyed From 程序人生 
Home Page:http://www.programlife.net 
Source URL:http://www.programlife.net/cpp-ostringstream-covert-to-string.html


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: C++中将字符串转换为double类型可以使用`std::stod`函数。该函数接受一个字符串参数,并返回其对应的double类型值。 示例代码如下: ```cpp #include <iostream> #include <string> int main() { std::string str = "3.14"; // 待转换的字符串 double num = std::stod(str); // 转换为double类型 std::cout << "转换后的值为: " << num << std::endl; return 0; } ``` 在上述代码中,我们声明一个std::string类型的变量`str`并初始化为字符串"3.14"。然后,我们使用`std::stod`函数将该字符串转换为double类型,并赋值给变量`num`。最后,我们打印出转换后的值。 输出结果为: ``` 转换后的值为: 3.14 ``` 这样就完成了将字符串转换为double类型的操作。 ### 回答2: 在C++中,我们可以使用stod函数将C字符串转换为double类型。stod函数是C++提供的字符串double的标准库函数,其函数原型为: double stod(const string& str, size_t* idx = 0); 其中,str是要转换的字符串,idx是一个指针参数,用于存储转换后字符串结束的位置。例如,我们有一个C字符串cstr,想要将其转换为double类型d: ```cpp #include <iostream> #include <string> int main() { const char* cstr = "3.1415926"; std::string str(cstr); double d = std::stod(str); std::cout << d << std::endl; // 输出 3.1415926 return 0; } ``` 在上述代码中,我们首先将C字符串cstr转换为std::string类型的str。然后,我们使用std::stod函数将str转换为double类型的d。最后,通过std::cout输出d的值。 需要注意的是,如果字符串不能被正确转换为double类型,stod函数会抛出std::invalid_argument异常。因此,在使用stod函数时,可以通过异常处理来处理转换失败的情况。 ### 回答3: 在C++中将字符串转换为双精度浮点数可以使用`stod`函数。这个函数是在`<string>`头文件中定义的,它接受一个字符串作为参数,并返回对应的双精度浮点数。 使用`stod`函数的示例代码如下: ```cpp #include <iostream> #include <string> int main() { std::string str = "3.14"; double num = std::stod(str); std::cout << "字符串 \"" << str << "\" 转换为双精度浮点数为:" << num << std::endl; return 0; } ``` 以上代码将字符串`"3.14"`转换为双精度浮点数,并打印结果`3.14`。 需要注意的是,如果字符串无法完全转换为双精度浮点数,或者不是一个有效的表示双精度浮点数的字符串,`stod`函数会抛出一个`std::invalid_argument`异常。因此,在使用`stod`函数进行类型转换时,需要对该异常进行适当的处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值