When using printf for string, I got :
string key = "123";
printf("Value is %s \n", key);
// output is: Value is < null >
But if I do it like this:
string key = "123";
printf("Value is: ");
printf(key.c_str());
then I get:
// output is: Value is 123
So what I did wrong with
printf %s
?
Thanks in advance.
std::stringis a C++ class. So this doesn’t work because:printfis a pure C function, which only knows how to deal with primitive types (int,double,char *, etc.).printfis a variadic function. Passing a class type to a variadic function leads to undefined behaviour.1If you want to display a string, use
std::cout:If you simply must use
printf, then this should work:c_stris a member function which returns a C-style string (i.e. aconst char *). Bear in mind that it has some restrictions; you cannot modify or delete thestringobject in-between callingc_str()and using the result:1. Or possibly implementation-defined, I don’t recall. Either way, it’s not going to end well.