Problems casting a const char* to char*

来源:互联网 发布:开淘宝代购店怎么申请 编辑:程序博客网 时间:2024/05/16 10:57

char *FileExt = path.c_str();

I continually get the error message saying that it is not possible to convert const char * to char *!

 

解决方法:

The c_str() method of the std::string class returns a pointer to const char so that you can't modify the result. Unfortunately, there's no good solution, and you can thank the author of the library who didn't write const-correct code. Now, if you know that the function will not modify the string, you can use const_cast to allow the conversion:

 

1、C++ Syntax (Toggle Plain Text)

 char *FileExt = const_cast ( path.c_str() );

 

If you're not sure whether the function will modify the string or not, you have no choice but to create a C-style string copy:

 

2、C++ Syntax (Toggle Plain Text)

char *FileExt = new char[path.size() + 1];

std::strcpy ( FileExt, path.c_str() );

原创粉丝点击