-2
system( "ping www.google.com  >  pingresult.txt") 

From this code can the string "ping www.google.com" be taken from an std::string variable? For example:

string ipAddress;

cout << "Enter the ip address: ";
cin >> ipAddress;

string ip = "ping" + ipAddress;
**system ("ip > pingresult.txt");** //error here
sytem("exit");
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
Zihaan
  • 1
  • 2

2 Answers2

0

ip is not a shell command. I'm guessing you thought the string "ip" in the system call would be implicitly replaced with the string ip in your program; it doesn't work that way.

You can put the entire command string in ip then use the .c_str() method to convert the string to the const char * array that system expects:

ip += " > pingresult.txt";
system(ip.c_str());
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
0

You must first build the full command into an std::string, and then pass it as a const char * to the system function:

string ipAddress;

cout << "Enter the ip address: ";
cin >> ipAddress;

string cmd = "ping " + ipAddress + " > pingresult.txt";
system (cmd.c_str()); // pass a const char *
//system("exit"); this is a no-op spawning a new shell to only execute exit...
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252