No suitable conversion function from “std::string” to “const char *” exists

别说谁变了你拦得住时间么 提交于 2020-02-14 04:10:07

问题


I am trying to delete a .txt file but the filename is stored in a variable of type std::string. The thing is, the program does not know the name of the file beforehand so I can't just use remove("filename.txt");

string fileName2 = "loInt" + fileNumber + ".txt";

Basically what I want to do is:

remove(fileName2);

However, it tells me that I cannot use this because it gives the me error:

No suitable conversion function from "std::string" to "const char *" exists.


回答1:


remove(fileName2.c_str());

will do the trick.

The c_str() member function of a std::string gives you the const char * C-style version of the string that you can use.




回答2:


You need to change it to:

remove(fileName2.c_str());

c_str() will return the string as a type const char *.




回答3:


When you need to convert std::string to const char* you can use the c_str() method.

std::string s = "filename";
remove(s.c_str());


来源:https://stackoverflow.com/questions/25778263/no-suitable-conversion-function-from-stdstring-to-const-char-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!