C++ std::要浮动或双精度的字符串

C++ std::要浮动或双精度的字符串,c++,C++,我正在尝试将std::string转换为float/double。 我试过: 但它总是返回零。还有其他方法吗?是的,使用词法转换。使用stringstream和词法转换非常好 #include <boost/lexical_cast.hpp> #include <iostream> #include <string> using std::endl; using std::cout; using std::string; using boost::lexic

我正在尝试将
std::string
转换为
float/double
。 我试过:


但它总是返回零。还有其他方法吗?

是的,使用词法转换。使用stringstream和词法转换非常好

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>

using std::endl;
using std::cout;
using std::string;
using boost::lexical_cast;

int main() {
    string str = "0.6";
    double dub = lexical_cast<double>(str);
    cout << dub << endl;
}
#包括
#包括
#包括
使用std::endl;
使用std::cout;
使用std::string;
使用boost::词法转换;
int main(){
字符串str=“0.6”;
双dub=词法转换(str);

cout您可以使用boost词法转换:

#include <boost/lexical_cast.hpp>

string v("0.6");
double dd = boost::lexical_cast<double>(v);
cout << dd << endl;
#包括
字符串v(“0.6”);
双dd=boost::词法转换(v);

cout如果您不想拖入所有boost,请使用
中的
strtod(3)
-它已经返回一个双精度

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>

using namespace std;

int main()  {
    std::string  num = "0.6";
    double temp = ::strtod(num.c_str(), 0);

    cout << num << " " << temp << endl;
    return 0;
}
#include <stdlib.h>
#include <string>

... 
  std::string num = "0.6";
  double temp = atof(num.c_str());
为什么atof()不工作…您使用的是什么平台/编译器

std::string num = "0.6";
double temp = ::atof(num.c_str());

对我来说,将字符串转换为双.< /P>是一种有效的C++语法。

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>

using namespace std;

int main()  {
    std::string  num = "0.6";
    double temp = ::strtod(num.c_str(), 0);

    cout << num << " " << temp << endl;
    return 0;
}
#include <stdlib.h>
#include <string>

... 
  std::string num = "0.6";
  double temp = atof(num.c_str());
您可以使用stringstream或boost::lexical_cast来实现这一点,但这些都会带来性能损失


啊哈,你有一个Qt项目

QString winOpacity("0.6");
double temp = winOpacity.toDouble();
额外说明:

如果输入数据是
常量字符*
QByteArray::toDouble
将更快。

您可以使用std::stringstream:

   #include <sstream>
   #include <string>
   template<typename T>
   T StringToNumber(const std::string& numberAsString)
   {
      T valor;

      std::stringstream stream(numberAsString);
      stream >> valor;
      if (stream.fail()) {
         std::runtime_error e(numberAsString);
         throw e;
      }
      return valor;
   }
#包括
#包括
模板
T StringToNumber(常量标准::字符串和数字字符串)
{
勇敢;
std::stringstream(numberAsString);
流>>勇气;
if(stream.fail()){
std::运行时错误e(NumberString);
投掷e;
}
回报勇气;
}
用法:

double number= StringToNumber<double>("0.6");
double number=stringtonnumber(“0.6”);

这个答案支持你评论中的litb。我怀疑你只是没有正确显示结果


有一次,我也遇到了同样的事情。我花了一整天的时间试图弄清楚为什么我将一个坏值转换成64位int,结果却发现printf忽略了第二个字节。你不能将一个64位的值像int一样传递给printf。

与其将Boost拖到等式中,不如保留你的字符串(暂时)作为
char[]
并使用
sprintf()


<>当然,如果你使用Boost,这不是太大的问题。

< P> C++是使用STD::STOD和STD::toSype。这两种方法都在Visual Studio 11中工作。

< P>关于为什么<代码> ATF()
在最初的问题中不起作用:它被强制转换为double的事实让我怀疑。如果没有
#include
,代码不应该编译,但是如果强制转换是为了解决编译警告而添加的,那么
atof()
就没有正确声明。如果编译器假定
atof()
返回一个int,强制转换它将解决转换警告,但不会导致返回值被识别为double

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>

using namespace std;

int main()  {
    std::string  num = "0.6";
    double temp = ::strtod(num.c_str(), 0);

    cout << num << " " << temp << endl;
    return 0;
}
   double myAtof ( string &num){
      double tmp;
      sscanf ( num.c_str(), "%lf" , &tmp);
      return tmp;
   }
#include <stdlib.h>
#include <string>

... 
  std::string num = "0.6";
  double temp = atof(num.c_str());
#包括
#包括
... 
std::string num=“0.6”;
双温=atof(num.c_str());
应在没有警告的情况下工作。

标准库(C++11)提供了所需的功能,包括:


一般来说,对于大多数其他基本类型,请参见。C字符串也有一些新功能。请参见,我在Linux中遇到了相同的问题

double s2f(string str)
{
 istringstream buffer(str);
 double temp;
 buffer >> temp;
 return temp;
}

它是有效的。

无论如何,你都不希望对字符串浮点进行Boost词法转换。对于Boost始终比旧函数差的用例子集,它们基本上将所有故障都集中在那里,因为它们自己的性能结果显示,性能比使用sscanf和printf慢20-25倍对于这样的转换

Google it yourself.boost::lexical_cast可以处理大约50次转换,如果排除涉及浮点的转换,则与其他明显的转换一样好或更好(还有一个额外的优势,就是所有这些操作都有一个API).但引入浮标,就性能而言,就像泰坦尼克号撞上冰山一样

旧的专用str->double函数都可以在大约30毫秒(或更高)的时间内完成10000次解析。词法转换需要大约650毫秒来完成相同的工作。

我的问题:

  • 与区域设置无关的字符串为双精度(十进制分隔符始终为“.”)
  • 字符串转换失败时的错误检测
  • 我的解决方案(使用Windows函数_wcstod_l):

    HTH…我花了很长时间才找到这个解决方案。我仍然觉得我对字符串本地化和其他东西了解得不够…

    使用C++17,你可以使用,这是一个比
    std::stof
    std::stod
    更轻巧、更快的替代方案。它不涉及任何内存分配或查看区域设置,我t是非投掷

    std::from_chars
    函数返回一个类型为
    from_chars_result
    的值,该值基本上是一个包含两个字段的结构:

    struct from_chars_result {
        const char* ptr;
        std::errc ec;
    };
    
    通过检查
    ec
    我们可以判断转换是否成功:

    #include <iostream>
    #include <charconv>
    
    int main()
    {
        const std::string str { "12345678901234.123456" };
        double value = 0.0;
        auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
        if (ec != std::errc()) {
            std::cout << "Couldn't convert value";
        }
        
        return 0;
    }
    
    #包括
    #包括
    int main()
    {
    const std::string str{“1234567890134.123456”};
    双值=0.0;
    auto[p,ec]=std::from_chars(str.data(),str.data()+str.size(),value);
    如果(ec!=std::errc()){
    
    std::忍不住过度设计十年前已经解决的问题。你确定输出正确吗?它不应该产生零。此外,你不需要强制转换atof,它已经返回双精度。我确定。调试器显示0。结果是0。平台:Linux。你确定安装了正确的区域设置吗?请尝试“0,6”或者setlocale(LC_NUMERIC,“C”);使用stringstream不需要boosty您的方法也会返回零。Linux.boost::lexical_cast是流式处理。我认为,您一般不能说它们会带来性能损失。试想一下,在使用cin>>num;之前会发生什么情况。用户必须非常快速地键入(类似于Ry jon skeet)请注意,词法转换的速度较慢:)也就是说,我相信有些任务的词法转换性能太差:)对于这个解决方案,atof()前面的::做什么?它需要在那里做什么?@ShaChris
    #include <iostream>
    #include <charconv>
    
    int main()
    {
        const std::string str { "12345678901234.123456" };
        double value = 0.0;
        auto [p, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
        if (ec != std::errc()) {
            std::cout << "Couldn't convert value";
        }
        
        return 0;
    }