2009-07-14 146 views
27

Possible Duplicate:
How do I convert a double into a string in C++?将double转换为字符串C++?

欲字符串结合和双和g ++引发此错误:

main.cpp中:在函数 '诠释主()':
main.cpp中:40:错误:类型“为const char [2]”的无效操作数和“双”为二进制“运算符+”

这里是其所投掷错误代码的行:

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

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

+11

如何从以下的一些例子:http://www.codeproject.com/KB/recipes/Tokenizer.aspx他们是非常有效的,有点优雅。 – 2010-11-02 05:03:53

+0

http://stackoverflow.com/q/29200635/395461 – Shannon 2015-03-22 23:20:58

回答

22

使用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风格的字符串搞乱。

+0

实际上`boost :: lexical_cast`不会在引擎盖下使用`std :: stringstream`。它实现了自己的转换例程,比使用`stringstream`快得多,并且在大多数情况下比`scanf` /`printf`快。请参阅:http://www.boost.org/doc/libs/1_48_0/doc/html/boost_lexical_cast/performance.html – Ferruccio 2011-12-09 11:47:38

+0

“lexical_cast”的来源看起来与我上次看到的有很大不同。在过去的几个Boost版本中,它们似乎已经有了相当大的提升。如果可以的话,更有理由采用它。 – 2011-12-09 13:51:24

71

你不能直接做。有许多方法可以做到这一点:

  1. 使用std::stringstream

    ​​
  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; 
    

还有很多其他的方法,使用各种双字符串转换函数,但这些是您看到它完成的主要方法。

26

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

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