C++ Output String: cout vs printf

In C++, strings can be output using either the std::cout or std::printf functions.

The method of outputting a string using std::cout is as follows:

#include <iostream>

int main() {
    std::string str = "Hello, World!";
    std::cout << str << std::endl;
    return 0;
}

The method of outputting strings using std::printf is as follows:

#include <iostream>

int main() {
    std::string str = "Hello, World!";
    std::printf("%s\n", str.c_str());
    return 0;
}

Note: When using std::printf to output a string, you need to convert the std::string type to a C-style string using the c_str method.

bannerAds