Home Ask Login Register

Developers Planet

Your answer is one click away!

OpenGL Maniac February 2016

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.


David Schwartz February 2016

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.

DOUGLAS O. MOEN February 2016

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*

Post Status

Asked in February 2016
Viewed 2,728 times
Voted 9
Answered 2 times


Leave an answer

Quote of the day: live life