mercredi 8 août 2018

Convert std::string to const char* for printf Consumption

Let us consider the below code example. Basically, getMessage1 (internally) creates an std::string which is meant to be returned and then printed via printf. How do I convert/cast/manipulate variable myString so that the output looks like the one from getMessage2?

I am aware that getMessage3 works, but it requires me to include .c_str() in every printf statement (and I'd like to avoid this extra suffix).

#include <string>

const char* getMessage1() {
    std::string myString = "SomeOutput";
    return myString.c_str();
}

const char* getMessage2() {
    return "SomeOutput"; 
}

std::string getMessage3() {
    std::string myString = "SomeOutput";
    return myString;
}

int main() {
    printf("#1: %s \n", getMessage1());         // prints #1: ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠¿ⁿ9"w
    printf("#2: %s \n", getMessage2());         // prints #2: SomeOutput
    printf("#3: %s \n", getMessage3().c_str()); // prints #3: SomeOutput

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire