问题
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