C ++将字符串转换为双精度型 [英] C++ Converting a String to Double

查看:206
本文介绍了C ++将字符串转换为双精度型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找到这一整天的解决方案!您可以将此标记为重新发布,但我真正寻找的是一个解决方案不使用boost词法转换。一个传统的C ++方式,这将是巨大的。我试过这个代码,但它返回一组乱码和字母。

  
double lineconverted;

istringstream buffer(line);
lineconverted;
buffer>>线性转换

我试过这个,但它总是返回0。

  stringstream convert(line); 
if(!(convert>> lineconverted)){
lineconverted = 0;
}

提前感谢:)



编辑:对于我使用的第一个解决方案(gibberish)..这是一个快照

解决方案

  #include< sstream& 

int main(int argc,char * argv [])
{
double f = 0.0;

std :: stringstream ss;
std :: string s =3.1415;

ss<< s;
ss>> F;

cout<< F;好的是,这个解决方案也适用于其他人,比如ints,



如果你想重复使用相同的缓冲区,你必须在 ss.clear 之间。 / p>

还有一个较短的解决方案,您可以在其中将值初始化为字符串流,并同时将其刷新为双精度:

  #include< sstream> 
int main(int argc,char * argv []){
stringstream(3.1415)>> f;
}


I've been trying to find the solution for this all day! You might label this as re-post but what I'm really looking for is a solution without using boost lexical cast. A traditional C++ way of doing it would be great. I tried this code but it returns a set of gibberish numbers and letters.

string line; 
double lineconverted;

istringstream buffer(line);
lineconverted;
buffer >> lineconverted;

And I alse tried this, but it ALWAYS returns 0.

stringstream convert(line);
if ( !(convert >> lineconverted) ) {
    lineconverted  = 0;
}

Thanks in advance :)

EDIT: For the first solution I used (gibberish).. Here's a snapshot

解决方案

#include <sstream>

int main(int argc, char *argv[])
{
    double f = 0.0;

    std::stringstream ss;
    std::string s = "3.1415";

    ss << s;
    ss >> f;

    cout << f;
}

The good thing is, that this solution works for others also, like ints, etc.

If you want to repeatedly use the same buffer, you must do ss.clear in between.

There is also a shorter solution available where you can initialize the value to a stringstream and flush it to a double at the same time:

#include <sstream>
int main(int argc, char *argv[]){
   stringstream("3.1415")>>f ;
}

这篇关于C ++将字符串转换为双精度型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆