C++ 将字符串转换为双精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16747915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 20:36:55  来源:igfitidea点击:

C++ Converting a String to Double

c++stringclassdouble

提问by PJ_Boy

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.

我一整天都在努力寻找解决方案!您可能会将其标记为重新发布,但我真正要寻找的是不使用 boost lexical cast的解决方案。一种传统的 C++ 方式会很棒。我试过这段代码,但它返回一组乱码数字和字母。

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 enter image description here

编辑:对于我使用的第一个解决方案(胡言乱语)..这是一个快照 在此处输入图片说明

回答by Devolus

#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.

好消息是,这个解决方案也适用于其他人,比如 ints 等。

If you want to repeatedly use the same buffer, you must do ss.clearin 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:

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

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

回答by awesoon

Since C++11 you could use std::stodfunction:

从 C++11 开始,您可以使用std::stod函数:

string line; 
double lineconverted;

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

But solution with std::stringstreamalso 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;
}

回答by Avraam Mavridis

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

}