My understanding is that string is a member of the std namespace, so why does the following occur?
#include <iostream>
int main()
{
using namespace std;
string myString = "Press ENTER to quit program!";
cout << "Come up and C++ me some time." << endl;
printf("Follow this command: %s", myString);
cin.get();
return 0;
}

Each time the program runs, myString prints a seemingly random string of 3 characters, such as in the output above.
C++23 Update
We now finally have
std::printas a way to usestd::formatfor output directly:This combines the best of both approaches.
Original Answer
It’s compiling because
printfisn’t type safe, since it uses variable arguments in the C sense1.printfhas no option forstd::string, only a C-style string. Using something else in place of what it expects definitely won’t give you the results you want. It’s actually undefined behaviour, so anything at all could happen.The easiest way to fix this, since you’re using C++, is printing it normally with
std::cout, sincestd::stringsupports that through operator overloading:If, for some reason, you need to extract the C-style string, you can use the
c_str()method ofstd::stringto get aconst char *that is null-terminated. Using your example:If you want a function that is like
printf, but type safe, look into variadic templates (C++11, supported on all major compilers as of MSVC12). You can find an example of one here. There’s nothing I know of implemented like that in the standard library, but there might be in Boost, specificallyboost::format.[1]: This means that you can pass any number of arguments, but the function relies on you to tell it the number and types of those arguments. In the case of
printf, that means a string with encoded type information like%dmeaningint. If you lie about the type or number, the function has no standard way of knowing, although some compilers have the ability to check and give warnings when you lie.