簡體   English   中英

如何在C ++ Sprintf 2nd(格式)參數中傳遞變量?

[英]How to pass variable in C++ Sprintf 2nd(format) argument?

我一直在討論如何在C ++中實現這一目標:

string format = "what is your %s";  
new_string = sprintf(buffer, format, name);

任何幫助將非常感謝。

謝謝!

使用format.c_str()

string format = "what is your %s";  
int total = sprintf(buffer, format.c_str(), name);

另請注意,返回的值不是新字符串,而是輸出字符串的緩沖區 返回的值實際上是寫入的字符總數。 此計數不包括自動附加在字符串末尾的附加空字符。 失敗時,返回負數( 請參閱此處的doc )。

但是在C ++中, std::ostringstream更好,類型安全,正如@Joachim在他的回答中所解釋的那樣。

使用ostringstream

std::ostringstream os;
os << "what is your " << name;
std::string new_string = os.str();

你總是可以這樣做:

char buffer[100]; 
string format = "what is your %s";
sprintf(buffer, format.c_str(), name.c_str());
string new_string(buffer);

或者,使用stringstream

stringstream buf;
buf << "what is your " << name;
string new_string = buf.str();

傳遞給sprintf的格式必須是char* ,而不是std::string sprintf還返回寫入的字符數,而不是指向構造緩沖區的指針。

int len = sprintf(buffer, "what is your%s", name);
std::string new_string(buffer, len);

另一種可能性是使用std::ostringstream來執行格式化。

我不確定我在這里理解這個問題 - sprintf是一個函數,它接受一個char*作為它的第一個參數,一個const char*作為它的第二個參數。 這些都是C數據類型,因此我不知道使用C ++字符串是否會被編譯器識別為有效。

此外,該函數返回一個int(寫入的字符數),而不是一個字符串,它看起來像你期望的返回值,如new_string

有關詳細信息,請參閱http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/

您可以使用C ++ STL中的stringstream ,這是更多的OO。

查看文檔

sprintf是C庫的一部分,因此對std :: string一無所知。 如果您仍想使用它,請使用char *。

要從std::string獲取C char* std::string ,請使用c_str方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM