std :: string.c_str()返回一个奇怪的字符 [英] std::string.c_str() returning a weird characters

查看:117
本文介绍了std :: string.c_str()返回一个奇怪的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我通常通过指定其文件名来加载纹理。现在,我使此函数 const char * app_dir(std :: string fileToAppend); 返回 main s argv [0] 并通过 fileToAppend 更改应用程序名称。由于无法使用char *来简化字符串操作,因此使用 std :: string 。我的纹理加载器将const char *作为文件名,因此需要切换回c_str(),现在它会生成一系列ASCII符号字符(错误)。我已经通过将 app_dir()的返回类型更改为 std :: string 来解决此问题。但是为什么会这样呢?

In my project, I use to load textures by specifying its file name. Now, I made this function const char* app_dir(std::string fileToAppend); that returns the mains argv[0] and change the application name by the fileToAppend. Since I cannot make the string manipulation easy with a char*, I use the std::string. My texture loader takes a const char* for file name so need to switch back to c_str(), now it generates a sequence of ASCII symbol characters (bug). I already fix the problem by changing the return type of the app_dir() to std::string. But why is that happening?

EDIT

示例代码:

//in main I did this

extern std::string app_filepath;

int main(int argc, char** arv) {

    app_filepath = argv[0];

    //...

}

//on other file

std::string app_filepath;

void remove_exe_name() {

    //process the app_filepath to remove the exe name

}

const char* app_dir(std::string fileToAppend) {

    string str_app_fp = app_filepath;

    return str_app_fp.append(fileToAppend).c_str();

    //this is the function the generates the bug

}

我已经通过将其返回类型更改为std :: string来使它正常工作。

I already have the functioning one by changing its return type to std::string as I said earlier.

推荐答案

当您使用函数 const char * app_dir(std :: string fileToAppend); 时,您将获得指向堆栈上已分配并在函数结束时已删除的内存的指针。

When you using function const char* app_dir(std::string fileToAppend); you get pointer to the memory that allocated on the stack and already deleted when the function ends.

这篇关于std :: string.c_str()返回一个奇怪的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆