【问题标题】:using a string variable to ping and save a file in C++ [duplicate]使用字符串变量在 C++ 中 ping 并保存文件 [重复]
【发布时间】:2017-01-18 17:15:03
【问题描述】:
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");

【问题讨论】:

  • 错误是什么?

标签: c++ system stdstring


【解决方案1】:

ip 不是 shell 命令。我猜你认为system 调用中的字符串"ip" 会被你程序中的字符串ip 隐式替换;那样不行。

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

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

【讨论】:

    【解决方案2】:

    您必须首先将完整的命令构建成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...
    

    【讨论】:

    • 现在我做对了,非常感谢!
    猜你喜欢
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-12-17
    • 2019-07-06
    • 2013-12-09
    相关资源
    最近更新 更多