簡體   English   中英

C ++將const char *與字符串連接,僅輸出const char *

[英]C++ Concatenating const char * with string, only const char * prints

我正在嘗試引用const char *

這就是我將int轉換為字符串並將其與const char *連接的方式

char tempTextResult[100];
const char * tempScore = std::to_string(6).c_str();
const char * tempText = "Score: ";
strcpy(tempTextResult, tempText);
strcat(tempTextResult, tempScore);
std::cout << tempTextResult;

打印時的結果是:分數:

有誰知道為什么6不打印?

提前致謝。

正如c_str文檔所說,“返回的指針可能會因進一步調用修改該對象的其他成員函數而無效。” 這包括析構函數。

const char * tempScore = std::to_string(6).c_str();

這使tempScore指向不再存在的臨時字符串。 你應該做這個:

std::string tempScore = std::to_string(6);
...
strcat(tempTextResult, tempScore.c_str());

在這里,您正在繼續存在的字符串上調用c_str

您已將此帖子標記為C ++。

一種可能的C ++方法:(未經編譯,未經測試)

std::string result;  // empty string
{
   std::stringstream ss;
   ss << "Score: "  // tempText literal
      << 6;         // tempScore literal
   // at this point, the values placed into tempTextResult 
   //    are contained in ss
   result = ss.str();    // because ss goes out of scope
}
// ss contents are gone

// ...   many more lines of code

// ... now let us use that const char* captured via ss
std::cout << result.c_str() << std::endl;
//                  ^^^^^^^ - returns const char*

暫無
暫無

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

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