system() does not accept string type variable in c++

Asked

Viewed 361 times

1

In order to automate some backups that need to be done routinely, so I thought of using an dos to do, but I’m having trouble compiling the executable because it seems to me that the function system() only accepts char variables, the code I used was the following.

#include <iostream>
#include <cstdlib>

using namespace std;
int main() {
string usuarios[5] = {"usuario","usuario","usuario","usuario","usuario"};
string diretorios[5];
string path[28];
for (int i = 0; i < 5; ++i) {
    diretorios[i] = "mkdir c:\\backups\\"+usuarios[i];
    system(diretorios[i]);
    path[i] = "c:\\unisystem\\backup\\"+usuarios[i];
    system("exp system/abcd owner="+usuarios[i]+" file="+path[i]+"\\"+usuarios[i]+".dmp log="+path[i]+"\\"+usuarios[i]+".log compress=n");
}
cout << "O processo de backup terminou!"<< endl;
system("pause");
return 0;
}

there is another function I can replace the system() or I have to convert string to char?

1 answer

1


The function system is not a function originating from C++ but from the C language, so it receives const char* and not std::string. The C++ string is nothing more than an array of C characters encapsulated in a class, and has a method that returns a pointer to that array: c_str()

std::string texto = "Alguma coisa";
texto += " outra coisa";
std::system(texto.c_str());
  • It worked Thank you! But then you mean that I reference the text variable information by the memory address it is occupying? So I don’t have to convert the guys?

  • 1

    It’s not converting, it’s just pointing. The pointer that c_str() returns, rather represents the location where the characters are, but when you use it the way I showed it, you’re "slipping" it, using it as a normal C string. If you want to display the memory address, then you would have to convert the pointer itself: std::cout << static_cast<void*>(&minhaString[0]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.