Consider the MWE below,
std::string return_string()
{
return "this is a string"
}
int main()
{
const char *y = return_string().c_str();
std::string str = return_string();
const char *x = str.c_str();
std::cout << return_string() << std::endl; //Prints "this is a string"
std::cout << y << std::endl; // Prints Weird characters
std::cout << x << std::endl; //Prints "this is a string"
std::cin.ignore();
return 0;
}
I have a function which returns a string and I need to convert it to a c-style string. Doing return_string().c_str()
gives me weird output like
▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌▌p
. But if I store the output of a function in a string first and then convert that string to a c-style string it works. What is wrong with the first way?