There is no suitable conversion function from "std :: string" to "const char *"

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

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

Basically what I want to do:

 remove(fileName2); 

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

There is no suitable conversion function from "std :: string" to "const char *".

+5
source share
3 answers
 remove(fileName2.c_str()); 

will do the trick.

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

+14
source

You need to change it to:

 remove(fileName2.c_str()); 

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

+3
source

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()); 
+1
source

Source: https://habr.com/ru/post/1202296/


All Articles