简体   繁体   English

C ++将字符串转换为Double

[英]C++ Converting a String to Double

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 . 你可能会把它标记为重新发布,但我真正想要的是一个不使用boost lexical cast的解决方案。 A traditional C++ way of doing it would be great. 传统的C ++方式很棒。 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. 我也试过这个,但它总是返回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. 如果要重复使用相同的缓冲区,则必须在两者之间执行ss.clear

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: 还有一个更短的解决方案,您可以将值初始化为字符串流并同时将其刷新为double:

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

Since C++11 you could use std::stod function: 从C ++ 11开始,您可以使用std::stod函数:

string line; 
double lineconverted;

try
{
    lineconverted = std::stod(line);
}
catch(std::invalid_argument)
{
    // can't convert
}

But solution with std::stringstream also correct: 但是使用std::stringstream解决方案也是正确的:

#include <sstream>
#include <string>
#include <iostream>

int main()
{
    std::string str;
    std::cin >> str;
    std::istringstream iss(str);
    double d = 0;
    iss >> d;
    std::cout << d << std::endl;
    return 0;
}

If you want to store (to a vector for example) all the doubles of a line 如果你想存储(例如矢量)一行的所有双打

#include <iostream>
#include <vector>
#include <iterator>

int main()
{

  std::istream_iterator<double> in(std::cin);
  std::istream_iterator<double> eof;
  std::vector<double> m(in,eof);

  //print
  std::copy(m.begin(),m.end(),std::ostream_iterator<double>(std::cout,"\n"));

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM