I have a program where I want to output a list of strings to a console window.
These strings come from my food.getFoodName() method (which returns a string) like "Steak", "Burger", "Sausage" etc.
I'm outputting these strings using a loop. Before I can output these strings, I need to convert the current string in the loop to a const char* so I can use it in my Draw_String() Method.
This is the code concerned in this process:
void DisplayFood(std::vector<Food> foods)
{
for (int i = 0; i < foods.size(); i++)
{
const char * c = foods.at(i).getFoodName().c_str();
Draw_String(10, i, c);
}
}
inline void Draw_String(int x, int y, const char *string)
{
// this function draws a string at the given x,y
COORD cursor_pos; // used to pass coords
// set printing position
cursor_pos.X = x;
cursor_pos.Y = y;
SetConsoleCursorPosition(hconsole, cursor_pos);
// print the string in current color
printf("%s", string);
} // end Draw_String
std::string Food::getFoodName()
{
return FoodName;
}
My issue is, this conversion doesn't work as intended, and my output on the screen is basically unreadable ascii symbols like "||||||||||||||||||"
I'm a noob at c++, only been doing this for like 10 weeks. But the issue is either the conversion process (most likely) or the printf method.
Anyone have any idea what I'm doing wrong? I'd appreciate any help.
foods.at(i).getFoodName()
returns a temporary object, which ends its lifetime after the statement, including the data returned by std::string::c_str
. So, accessing the memory pointed to by c
is undefined behavior.
Instead, you could
extend the temporary's lifetime by binding it to a const
reference:
const std::string& foodName = foods.at(i).getFoodName();
since C++11, bind it to an rvalue reference:
std::string&& foodName = foods.at(i).getFoodName();
just pass the temporary to the function directly:
Draw_String(10, i, foods.at(i).getFoodName().c_str());
return a reference from Food::getFoodName
1.
You might also have a look at this thread.
Notes:
Why don't you use std::string
? std::cout
will work fine with it.
std::printf
should not be used in usual C++ code.
1 As proposed by @juanchopanza in the comments to this answer
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments