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.
You can use the c_str() method of the string class to get a const char* with the string contents.
The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0'). It returns a null pointer to the string.
In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...
const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed.
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.
You need to change it to:
remove(fileName2.c_str());
c_str()
will return the string as a type const char *
.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With