C++ 使用字符串变量ping并将文件保存到C++;
从这个代码中,字符串C++ 使用字符串变量ping并将文件保存到C++;,c++,system,stdstring,C++,System,Stdstring,从这个代码中,字符串“ping www.google.com”可以从std::string变量中获取吗?例如: system( "ping www.google.com > pingresult.txt") 字符串IP地址; cout>ipAddress; 字符串ip=“ping”+ipAddress; **系统(“ip>pingresult.txt”);**//这里出错 系统(“出口”); ip不是shell命令。我猜您认为系统调用中的字符串“ip”将被程序中的字符串ip隐式替换
“ping www.google.com”
可以从std::string
变量中获取吗?例如:
system( "ping www.google.com > pingresult.txt")
字符串IP地址;
cout>ipAddress;
字符串ip=“ping”+ipAddress;
**系统(“ip>pingresult.txt”);**//这里出错
系统(“出口”);
ip
不是shell命令。我猜您认为系统
调用中的字符串“ip”
将被程序中的字符串ip
隐式替换;这样不行
您可以将整个命令字符串放入ip
中,然后使用.c_str()
方法将字符串转换为系统所需的常量字符*
数组:
string ipAddress;
cout << "Enter the ip address: ";
cin >> ipAddress;
string ip = "ping" + ipAddress;
**system ("ip > pingresult.txt");** //error here
sytem("exit");
必须首先将完整命令构建到std::string
,然后将其作为const char*
传递给系统
函数:
ip += " > pingresult.txt";
system(ip.c_str());
字符串IP地址;
cout>ipAddress;
字符串cmd=“ping”+ipAddress+“>pingresult.txt”;
系统(cmd.c_str());//传递一个常量字符*
//系统(“退出”);这是一个无操作生成一个新的shell,只执行退出。。。
有什么错误?好吧,现在我答对了,非常感谢!
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...