2010-06-02 44 views
1

我正在使用VS2008 C++。C++將格式化的字符串轉換爲流

據我所知是沒有辦法通過在C++流是這樣的:(不使用外部庫)

"number " << i <------ when i is an integer. 

所以我一直在尋找更好的方式來做到這一點,和我所有我能想出的是創建一個字符串使用:

char fullstring = new char[10]; 
sprintf(fullString, "number %d", i); 
.... pass fullstring to the stream ..... 
delete[] fullString; 

我知道這是愚蠢的,但有沒有更好的方式做到這一點?

回答

4
std::ostringstream oss; 
oss << "number " << i; 
call_some_func_with_string(oss.str()); 
4

你還打擾到試試

int i = 3; 
std::cout << "number " << i; 

工作得很好,自然也應該適用於任何流。

2

試試這個:

#include <sstream> 
// [...] 
std::ostringstream buffer; 
int i = 5; 
buffer << "number " << i; 
std::string thestring = buffer.str(); // this is the droid you are looking for 
相關問題