简体   繁体   中英

C++ Concatenating const char * with string, only const char * prints

I am trying to cout a const char *

This is how I convert an int to a string and concatenate it with the 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;

The result when printing is: Score:

Does anyone know why the 6 is not printing?

Thanks in advance.

As the docs for c_str say, "The pointer returned may be invalidated by further calls to other member functions that modify the object." This includes the destructor.

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

This makes tempScore point to a temporary string that no longer exists. You should do this:

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

Here, you're calling c_str on a string that continues to exist.

You have marked this post as C++.

One possible C++ approach: (not compiled, not tested)

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*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM