Home >Backend Development >C++ >How Can I Use printf with a std::string in C ?
printf is a C function, and std::string is a C class. That's why you're getting the error.
To fix this, you can use the c_str() method of std::string to get a C-style string that you can pass to printf. For example:
#include <iostream> #include <string> #include <stdio.h> 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.c_str()); cin.get(); return 0; }
This will output:
Come up and C++ me some time. Follow this command: Press ENTER to quit program!
If you don't want to use c_str(), you can also use the string stream class to format your output. For example:
#include <iostream> #include <string> #include <sstream> int main() { using namespace std; string myString = "Press ENTER to quit program!"; cout << "Come up and C++ me some time." << endl; ostringstream oss; oss << "Follow this command: " << myString; printf("%s", oss.str().c_str()); cin.get(); return 0; }
This will output the same as the previous example.
The above is the detailed content of How Can I Use printf with a std::string in C ?. For more information, please follow other related articles on the PHP Chinese website!