我有一个程序要在其中将字符串列表输出到控制台窗口。
这些字符串来自我的food.getFoodName()方法(返回一个字符串),例如“ Steak”,“ Burger”,“ Sausage”等。
我正在使用循环输出这些字符串。在输出这些字符串之前,需要将循环中的当前字符串转换为const char *,以便可以在Draw_String()方法中使用它。
这是此过程中涉及的代码:
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;
}
我的问题是,这种转换无法正常工作,并且我在屏幕上的输出基本上是无法读取的ASCII符号,如“ ||||||||||||||||||||”
我是C ++的新手,只做了10个星期。但是问题是转换过程(最有可能)或printf方法。
有人知道我在做什么错吗?我将不胜感激。
foods.at(i).getFoodName()
返回一个临时对象,该对象的寿命在该语句之后(包括所返回的数据)结束 std::string::c_str
。因此,访问由指向的内存c
是未定义的行为。
相反,您可以
通过将其绑定到const
引用来延长临时文件的寿命:
const std::string& foodName = foods.at(i).getFoodName();
从C ++ 11开始,将其绑定到右值引用:
std::string&& foodName = foods.at(i).getFoodName();
只需将临时变量直接传递给函数:
Draw_String(10, i, foods.at(i).getFoodName().c_str());
从Food::getFoodName
1返回引用。
您可能还会对此线程有所了解。
笔记:
你为什么不使用 std::string
?std::cout
会很好用的。
std::printf
不应在常规C ++代码中使用。
1如@juanchopanza在对此答案的评论中所建议的
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句