Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从int到c字符串(const char*)的转换失败_C++_String_Pointers_Type Conversion_Cstring - Fatal编程技术网

C++ 从int到c字符串(const char*)的转换失败

C++ 从int到c字符串(const char*)的转换失败,c++,string,pointers,type-conversion,cstring,C++,String,Pointers,Type Conversion,Cstring,我无法将int转换为c字符串(const char*): int filenameIndex=1; stringstream temp_str; temp_str返回一个临时对象,该对象在语句末尾被销毁。因此,cstr2所指向的地址将失效 相反,请使用: int filenameIndex = 1; stringstream temp_str; temp_str<<(filenameIndex); std::string str = temp_str.str(); con

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

int filenameIndex=1;
stringstream temp_str;
temp_str返回一个临时对象,该对象在语句末尾被销毁。因此,
cstr2
所指向的地址将失效

相反,请使用:

int filenameIndex = 1;      
stringstream temp_str;
temp_str<<(filenameIndex);
std::string str = temp_str.str();
const char* cstr2 = str.c_str();
int filenameIndex=1;
stringstream temp_str;
temp_str
temp_str.str()
是一个临时的
字符串
值,在语句末尾销毁<然后,code>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

同样,这将通过值返回一个
字符串,所以不要尝试
cstr2=to_string(…).c_str()

我想这取决于您所说的“convert
int
to
char*
”是什么意思。
常量字符*
的“期望值”是多少?我希望它看起来很像“某个地址”
*cstr2
看起来更像
1
,而
temp\u str
在范围内。@约翰西韦布,如果你有更好的转换方法,我不介意删除
const
。顺便说一句:我会对变量使用
auto
,因为它需要C++11。@MikeSeymour,谢谢,我想使用
to_string
,但我得到了以下编译错误:“重载函数的多个实例:to_string”。缺少什么?@user3165438:假设您包含
(我猜您必须使用
字符串
),并且假设
文件名索引
具有所示的类型
int
,它应该可以工作。也许您已经将一个名为
的函数写入了_string
,在这种情况下,请使用
std::
对其进行限定。可能您有一个损坏的库:我似乎记得一些较旧版本的GNU库没有提供
to_string
的所有重载,在这种情况下,您需要显式地将不支持的类型转换为提供的类型(或更新编译器)。
string str = std::to_string(fileNameIndex);
const char* cstr2 = str.c_str();       // if you really want a C-style pointer