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 >...
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");
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...