Home > Backend Development > C++ > How Can I Use printf with a std::string in C ?

How Can I Use printf with a std::string in C ?

DDD
Release: 2024-12-16 01:06:10
Original
1000 people have browsed it

How Can I Use printf with a std::string in C  ?

printf with std::string

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;
}
Copy after login

This will output:

Come up and C++ me some time.
Follow this command: Press ENTER to quit program!
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template