2

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.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Hugius
  • 380
  • 1
  • 5
  • 15

2 Answers2

6

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.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

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*
2785528
  • 5,438
  • 2
  • 18
  • 20
  • Well, I needed it to be a const char *, and this looks like a string(I don't know what stringstream is so I am not sure) – Hugius Feb 08 '16 at 17:25
  • @OpenGLManiac Ok ... I've appended the c_str() so that the result out of ss is const char*. – 2785528 Feb 08 '16 at 17:28
  • Added reminder that the limited scope of ss (via braces) requires that I create and capture the ss contents to a result string .. for later use. – 2785528 Feb 08 '16 at 17:48
  • @OpenGLManiac -- std::stringstream can be considered a ram based stream ... simpler to use, works very much like fstream (but without open and close) and ram is somewhat faster than (most) alternatives. – 2785528 Feb 08 '16 at 17:52