将double转换为字符串C ++?

时间:2009-07-14 02:44:59

标签: c++ string double tostring

  

可能重复:
  How do I convert a double into a string in C++?

我想要组合一个字符串和一个double,而g ++会抛出这个错误:

main.cpp:在函数'int main()'中:
main.cpp:40:错误:类型'const char [2]'和'double'到二进制'operator +'的无效操作数

以下是抛出错误的代码行:

storedCorrect[count] = "("+c1+","+c2+")";

storedCorrect []是一个字符串数组,c1和c2都是双精度数。有没有办法将c1和c2转换为字符串以允许我的程序正确编译?

5 个答案:

答案 0 :(得分:72)

你不能直接这样做。有很多方法可以做到:

  1. 使用std::stringstream

    std::ostringstream s;
    s << "(" << c1 << ", " << c2 << ")";
    storedCorrect[count] = s.str()
    
  2. 使用boost::lexical_cast

    storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
    
  3. 使用std::snprintf

    char buffer[256];  // make sure this is big enough!!!
    snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
    storedCorrect[count] = buffer;
    
  4. 还有很多其他方法,使用各种双字符串转换功能,但这些是你看到它的主要方式。

答案 1 :(得分:27)

在C ++ 11中,use std::to_string如果您可以接受默认格式(%f)。

storedCorrect[count]= "(" + std::to_string(c1) + ", " + std::to_string(c2) + ")";

答案 2 :(得分:23)

使用std::stringstream。所有内置类型都会重载operator <<

#include <sstream>    

std::stringstream s;
s << "(" << c1 << "," << c2 << ")";
storedCorrect[count] = s.str();

这就像您期望的那样 - 与使用std::cout打印到屏幕的方式相同。你只是简单地“打印”到一个字符串。 operator <<的内部负责确保有足够的空间并进行必要的转换(例如doublestring)。

此外,如果您有可用的Boost库,您可以考虑查看lexical_cast。语法看起来很像普通的C ++风格的转换:

#include <string>
#include <boost/lexical_cast.hpp>
using namespace boost;

storedCorrect[count] = "(" + lexical_cast<std::string>(c1) +
                       "," + lexical_cast<std::string>(c2) + ")";

在幕后,boost::lexical_cast基本上与std::stringstream做同样的事情。使用Boost库的一个关键优势是您可以轻松地采用其他方式(例如,stringdouble)。不再混淆atof()strtod()和原始C风格的字符串。

答案 3 :(得分:10)

std::string stringify(double x)
 {
   std::ostringstream o;
   if (!(o << x))
     throw BadConversion("stringify(double)");
   return o.str();
 }

C ++常见问题解答: http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1

答案 4 :(得分:1)

我相信sprintf对你来说是正确的功能。我在标准库中,就像printf一样。请点击以下链接获取更多信息:

http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/