我无法将int
转换为c字符串(const char*
):
int filenameIndex = 1;
stringstream temp_str;
temp_str<<(fileNameIndex);
const char* cstr2 = temp_str.str().c_str();
没有错误,但cstr2
未获得预期值。它是用某个地址初始化的。
出了什么问题,我该如何解决?
temp_str.str()
返回一个临时对象,该对象在语句末尾被销毁。因此,cstr2
所指向的地址将无效。
相反,使用:
int filenameIndex = 1;
stringstream temp_str;
temp_str<<(filenameIndex);
std::string str = temp_str.str();
const char* cstr2 = str.c_str();
DEMO
temp_str.str()
是一个临时string
值,在语句末尾销毁。cstr2
就是一个悬空指针,当它指向的数组被字符串的破坏删除时,它就失效了。
如果你想保留一个指向它的指针,你需要一个非临时字符串:
string str = temp_str().str(); // lives as long as the current block
const char* cstr2 = str.c_str(); // valid as long as "str" lives
现代C++也有稍微更方便的字符串转换功能:
string str = std::to_string(fileNameIndex);
const char* cstr2 = str.c_str(); // if you really want a C-style pointer
同样,这会按值返回string
,所以不要尝试cstr2 = to_string(...).c_str()