System() no suitable conversion C++

2019-03-06 09:59发布

问题:

I have 2 lists with file names.

std::list<std::string> userfontlist;
std::list<std::string>::iterator it;
std::list<std::string> CAATfontlist;
std::list<std::string>::iterator it2;
std::list<std::string> doesnthavelist;

and I want to compare the 2 lists, and delete the value it matches. every seems to be fine until I add the "del /F /Q /A" to the y.c_string().

for (it = userfontlist.begin(); it !=userfontlist.end(); ++it){
    for(it2 = CAATfontlist.begin();it2 !=CAATfontlist.end();++it2){
        if(*it==*it2){
            string y = *it;
            string k = y.c_str();
            string a = "del /F /Q /A " + k;
            system(a);

        }
    }
 }

system(a) Says I have "no suitable conversion function from std string to const char * exists". If I put the whole thing as 1 string it works, but not when I concatenate the string and the y.c_str(). I have had no luck trying to convert the std::string to const *char, not even sure if that even helps.

回答1:

exactly as it says, there's no version of system() that understands std::string and std::string can't be freely converted to const char * (which system() does understand), because std::string may go away in ways that don't make sense in the general case.

you can explicitly convert from std::string to const char * easily, though: with std::string::c_str, write your last line as

system(a.c_str());

Be aware that the returned const char *'s lifetime is tied to the string it came from, once it goes out of scope, the pointer becomes invalid. This case is a fine time to use it, though, since system() won't "hold on" to the pointer past its own return.



标签: c++ system