Search code examples
c++systemxcopy

How to supply a string for the system() function in C++


I'm just getting back into C++ after a few yeas of not using it, and am trying to do an "xcopy" command through the system() function.

I assumed it would work just giving it a string so I did something like:

string command = "xcopy " + source + " " + string(1,cInternalDrive) + ":\\" + workspace + " /D /E /C /R /H /I /K /Y /EXCLUDE:" +  exclude;
system(command);

The value of command after setting it is "xcopy F:\Workspace*.* D:\Workspace\ /D /E /C /R /H /I /K /Y /EXCLUDE:F:\ignore.txt" which is the value that I want, but system() does not like the variable command.

It says Error: no suitable conversion function from :std::string" to "const char *" exists. After a bit of research I saw that system is supposed to take in a cstring type, not just a regular string, but after some testing I am unsure of how to implement it.


Solution

  • That's because c++ can't explicitly cast std::string to const char* You need to use std::string::c_str() function that will return const char* :

    system(command.c_str());