Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

casting

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.

like image 267
user3216887 Avatar asked Sep 11 '14 02:09

user3216887


People also ask

How do I get const char from STD string?

You can use the c_str() method of the string class to get a const char* with the string contents.

How do I convert a string to a char in C++?

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.

Can a char * be passed as const * argument?

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 ...

Can const char * Be Changed?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed.


3 Answers

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.

like image 192
paxdiablo Avatar answered Oct 23 '22 13:10

paxdiablo


You need to change it to:

remove(fileName2.c_str());

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

like image 43
PomfCaster Avatar answered Oct 23 '22 15:10

PomfCaster


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());
like image 30
justanothercoder Avatar answered Oct 23 '22 15:10

justanothercoder