【问题标题】:Confused how to convert from a string to double using strtod() in C++困惑如何在 C++ 中使用 strtod() 从字符串转换为双精度
【发布时间】:2011-08-06 22:24:40
【问题描述】:

如果有人能解释如何使用该功能,那就太好了。参数看不懂。

谢谢

【问题讨论】:

    标签: c++ strtod


    【解决方案1】:

    第一个参数是指向字符的指针。 c_str() 为您提供来自字符串对象的指针。第二个参数是可选的。它将在字符串中的数值之后包含一个指向下一个字符的指针。请参阅http://www.cplusplus.com/reference/clibrary/cstdlib/strtod/ 了解更多信息。

    string s;
    double d;
    
    d = strtod(s.c_str(), NULL);
    

    【讨论】:

      【解决方案2】:

      第一个参数是你要转换的字符串,第二个参数是一个 char* 的引用,你想指向原始字符串中浮点数之后的第一个字符(如果你想开始阅读数字后面的字符串)。如果您不关心第二个参数,您可以将其设置为 NULL。

      例如,如果我们有以下变量:

      char* foo = "3.14 is the value of pi"
      float pi;
      char* after;
      

      pi = strtod(foo, after) 之后的值将是:

      foo is "3.14 is the value of pi"
      pi is 3.14f
      after is " is the value of pi"
      

      注意 foo 和 after 都指向同一个数组。

      【讨论】:

        【解决方案3】:

        如果您使用 C++,那么为什么不使用std::stringstream

        std::stringstream ss("78.987");
        
        double d;
        ss >> d;
        

        或者,更好的是boost::lexical_cast

        double d;
        try
        {
            d = boost::lexical_cast<double>("889.978");
        }
        catch(...) { std::cout << "string was not a double" << std::endl; }
        

        【讨论】:

          猜你喜欢
          • 2011-07-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-07-09
          • 2022-01-20
          • 1970-01-01
          相关资源
          最近更新 更多