将字符串转换为字符*
Converting a string to a char*
我有一个程序,我想在其中向控制台窗口输出字符串列表。
这些字符串来自我的food.getFoodName()方法(返回字符串),如"Steak"、"Burger"、"Sausage"等。
我正在使用循环输出这些字符串。在输出这些字符串之前,我需要将循环中的当前字符串转换为constchar*,以便在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如@juancopanza在对该答案的评论中提出的
相关文章:
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 字符转换功能 std::isupper() & std::islower() C++17
- 将字符 * 转换为字符串 *
- 在编译时将常量字符* 转换为常量 char_type*
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 无法使用字符串流将字符转换为字符串C++
- 将无符号字符 C++ 转换为 C#
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 无法<string>从"常量字符 []"转换为<类名>
- 不能将字符转换为整数吗?
- 编译时将字符*转换为字节
- CP1251:从字符* 转换为 wchar_t* 时的编码失真
- 将单个字符转换为 std::string 前缀 \x01
- PPM 将字符转换为 int 授予负数
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 将常量字符* 转换为字符时出错