Using variables in C ++ system () function


  string line;
  ifstream myfile ("aaa.txt");
  getline (myfile,line);
  system("curl.exe -b cookie.txt -d test="+line+"  http://example.com");

And it doesn’t work! I also tried line.c_str (); But that didn't work either. Please help me.

+4
source share
3 answers

This does not work because you pass the C ++ string to the system () C function. c_str () may help, but you should apply it to the whole line:

system(("curl.exe -b cookie.txt -d test="+line+"  http://example.com").c_str());

, system() , , , . , , , . - "escape" spawn()/exec()/whatever else, .

+10

1:

, system :

int system (const char *command);

std::string.

- std::string, char, c_str().

string cmd("curl.exe -b cookie.txt -d test=");
cmd += line;
cmd += "  http://example.com";

system.

system(cmd.c_str());

2:

unvalidated unclean system , , .

.

+8

Create the string you pass system()with a string stream!

#include <sstream>
#include <fstream>
#include <string>
using namespace std;

int main(void){
    string line;
    ifstream myfile("aaa.txt");
    getline(myfile,line);
    stringstream call_line;
    call_line << "curl.exe -b cookie.txt -d test=" << line << "  http://example.com");
    system(call_line.str().c_str());
}
+3
source

All Articles