使用字符串变量ping并在C ++中保存文件

时间:2017-01-18 17:15:04

标签: c++ system stdstring

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

从此代码中可以从"ping www.google.com"变量获取字符串std::string吗?例如:

string ipAddress;

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

string ip = "ping" + ipAddress;
**system ("ip > pingresult.txt");** //error here
sytem("exit");

2 个答案:

答案 0 :(得分:0)

ip不是shell命令。我猜你认为"ip"调用中的字符串system将被隐含地替换为程序中的字符串ip;它不起作用。

您可以将整个命令字符串放在ip中,然后使用.c_str()方法将字符串转换为const char *期望的system数组:

ip += " > pingresult.txt";
system(ip.c_str());

答案 1 :(得分:0)

您必须先将完整命令构建到std::string,然后将其作为const char *传递给system函数:

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...