Using a String Variable to Ping and Save a File in C++ [Duplicate]
system( "ping   >  pingresult.txt") 

From this code can the string "ping " 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");
1

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());

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...
1
Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest