将字符串转换为字符*

Converting a string to a char*

本文关键字:字符 转换 字符串      更新时间:2023-10-16

我有一个程序,我想在其中向控制台窗口输出字符串列表。

这些字符串来自我的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::getFoodName1的引用。


你也可以看看这个帖子。


注:

  • 为什么不使用std::stringstd::cout可以很好地使用它。

  • std::printf不应在通常的C++代码中使用


1如@juancopanza在对该答案的评论中提出的