2009-07-14 144 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) + ")";