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

Men*_*yst 27 c++ string double tostring

可能重复:
如何在C++中将double转换为字符串?

我想组合一个字符串和一个双G ++正在抛出这个错误:

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

这是抛出错误的代码行:

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

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

Ada*_*eld 72

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

  1. 使用std::stringstream:

    std::ostringstream s;
    s << "(" << c1 << ", " << c2 << ")";
    storedCorrect[count] = s.str()
    
    Run Code Online (Sandbox Code Playgroud)
  2. 用途boost::lexical_cast:

    storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
    
    Run Code Online (Sandbox Code Playgroud)
  3. 用途std::snprintf:

    char buffer[256];  // make sure this is big enough!!!
    snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
    storedCorrect[count] = buffer;
    
    Run Code Online (Sandbox Code Playgroud)

还有许多其他方法,使用各种双字符串转换函数,但这些是您将看到它的主要方式.

  • 我知道这个答案很老,但你可能也想在这里包含`std :: string to_string(double);`. (5认同)

ken*_*ytm 27

在C++ 11,使用std::to_string,如果你能接受默认的格式(%f).

storedCorrect[count]= "(" + std::to_string(c1) + ", " + std::to_string(c2) + ")";
Run Code Online (Sandbox Code Playgroud)


Mic*_*fik 23

使用std::stringstream.operator <<对于所有内置类型,它都会过载.

#include <sstream>    

std::stringstream s;
s << "(" << c1 << "," << c2 << ")";
storedCorrect[count] = s.str();
Run Code Online (Sandbox Code Playgroud)

这可以像您期望的那样工作 - 就像您使用打印到屏幕一样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) + ")";
Run Code Online (Sandbox Code Playgroud)

在引擎盖下,boost::lexical_cast我们基本上做了同样的事情std::stringstream.使用Boost库的一个关键优势是您可以轻松地采用其他方式(例如,stringto double).不再乱用atof()strtod()原始C风格的字符串.


aJ.*_*aJ. 10

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

C++ FAQ:http: //www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.1