2011-12-24 69 views
2

我知道如何與COUT做到這一點:如何在C++中添加多個項目到字符串?

cout << "string" << 'c' << 33; 

但如何,而不是直接執行該所以輸出重定向到變量的標準了呢?

const char* string << "string" << 'c' << 33; //doesn't work 
+1

'char *'或'std :: string' ?? – Pubby 2011-12-24 20:21:40

回答

10

使用來自C++標準庫的std::stringstream

它的工作原理如下所示:

std::stringstream ss; 
ss << "string" << 'c' << 33; 
std::string str = ss.str(); 
const char* str_ansi_c = str.c_str(); 

記住str仍然需要在範圍內,而你正在使用C風格str_ansi_c

+0

stringstream不是STL的一部分。 – Pubby 2011-12-24 20:43:07

+0

@Pubby:不,它是C++標準庫的一部分。一個小小的步伐。但是,如果不是迂腐,電腦就什麼都不是。 – Omnifarious 2011-12-24 21:02:37

+0

Thx。修正了這個:) – Krizz 2011-12-24 21:32:41

2
#include <sstream> 
#include <iostream> 

main() 
{ 
    std::stringstream ss; 
    ss << "string" << 'c' << 33; 

    std::string str = ss.str(); 
    std::cout << str; 
} 
相關問題