1

I'm hoping that this will be a pretty basic problem that is maybe due to my lack of understanding a lot of the C++ Win32 API utlities.

Anyway, I'm having some trouble with the sprintf() function. I had no problem using it with a string like this:

//memory is a void pointer that maps a file to shared memory
sprintf((char *)memory, "Shared memory message"); //Write to shared memory

But when I try to use a string variable it doesn't work....

sprintf((char *)memory, str_var); //Write to shared memory

I get an error that says: no suitable conversion function from "std::string" to "const char *" exists. I am not even able to fix this by type casting, like I did with memory.

This seems pretty inconsistent. What am I doing wrong, and how do I give it a value that it will accept?

Eric after dark
  • 1,768
  • 4
  • 31
  • 79
  • 1
    std::string cannot be converted to const char*, use the .c_str() member method to convert it – David Szalai Nov 28 '14 at 20:22
  • try to learn difference between string and c-style string. [http://stackoverflow.com/questions/10958437/how-to-convert-an-stdstring-to-c-style-string][1] [1]: http://stackoverflow.com/questions/10958437/how-to-convert-an-stdstring-to-c-style-string – BufBills Nov 28 '14 at 20:32

1 Answers1

2

Iff you need sprintf, you need to pass a const char*:

So e.g.

sprintf((char *)memory, str_var.c_str()); 
sehe
  • 374,641
  • 47
  • 450
  • 633