从int转换为c字符串(const char *)失败

用户名

我无法转换int为C字符串(const char*):

int filenameIndex = 1;      
stringstream temp_str;
temp_str<<(fileNameIndex);
const char* cstr2 = temp_str.str().c_str();    

没有错误cstr2,但未获得预期值。它用一些地址初始化。

有什么问题,我该如何解决?

皮特·斯科特尼克(Piotr Skotnicki)

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();

演示

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사