【问题标题】:How to input multiple commands or loop a command in Command Prompt using C++?如何使用 C++ 在命令提示符中输入多个命令或循环命令?
【发布时间】:2018-07-25 21:37:26
【问题描述】:

我正在尝试实时显示我的命令的结果。我已经能够检索结果,但我想要一个实时流。每当我在我的代码中添加一个 while 循环来重复该命令时,就会打开一个窗口,执行该命令,然后关闭该窗口,然后打开另一个窗口并重复该过程,直到程序崩溃。我希望命令提示符在接收命令时在后台运行,因为我在它前面运行 QT gui。

这是我目前的代码:

cmd = _popen("snmpget -v 2c -c public 192.168.127.101 .1.3.6.1.4.1.8691.8.4.6.1.1.3.1.1.4.1", "r"); //input command in format (snmp_function -v version -c community_string IP_address OID)
if (cmd == NULL)
{
    perror("_popen");
    exit(EXIT_FAILURE);
}
while (fgets(result, sizeof(result), cmd))          //gets full responce string to snmpget and passes string to result variable
{
    std::string str = result;                       //sets string to values in variable result
    std::regex rgx("\"([^\"]*)\"");                 //retrieves only the section of the output string that is between double air quotes
    std::smatch match;
    std::string buffer;
    std::stringstream ss(str);
    std::vector<std::string> strings;
                                                //necessary? whitespace
    while (ss >> buffer)
        strings.push_back(buffer);
    for (auto& i : strings)
    {
        if (std::regex_match(i, match, rgx))
        {
            std::ssub_match submatch = match[1];
            std::string str = submatch.str();
            for (size_t j=0; j<str.length(); j++)
            {
                output[j] = str[j];
            }
        }
    }
}

_pclose(cmd);

std::string 的东西只是为了得到我想要的返回值的一部分。 我通常可以通过在包含此内容的 while 循环的末尾添加 getchar() 来保持窗口打开,但我不想依赖用户按 Enter 来获得更新的结果。

【问题讨论】:

  • 除非您的问题与 Qt 有关,否则您不应该使用该标签。
  • @RSahu 我在 Qt 中运行它。如果这是我自己的程序,我会完成,我需要它在我的 Qt gui 运行时运行。我在顶部提到这是在 Qt 中。
  • 我明白了。你是不是建议如果你在没有 Qt 的情况下运行上面的代码,你看不到任何问题?
  • @RSahu 是的,因为我可以保持打开状态并等待用户输入。作为我的 Qt 程序的一部分,它需要在没有用户输入的情况下被动发生。
  • 这对我来说没有意义。希望对其他人有意义。

标签: c++ qt cmd snmp


【解决方案1】:

我建议您在执行第一个命令时使用嵌套的 cmd。比如:

cmd.exe /c cmd.exe /k "Put the command you want to execute here!"

我不确定是否需要引用命令,但我知道它确实可以使用引号,这意味着您将第一行更改为:

cmd = _popen("cmd.exe /c cmd.exe /k \"snmpget -v 2c -c public 192.168.127.101 .1.3.6.1.4.1.8691.8.4.6.1.1.3.1.1.4.1\"", "r"); //Note the escaped quotes

以上内容未经测试,但我相信它应该会给您预期的结果。请注意,这每次都会打开一个内部 cmd,因此使用此解决方案您可能希望跟踪退出。基本上对于不是第一个命令的每个命令,您都需要发送 exit 以关闭该内部->内部 cmd。

【讨论】:

  • 不幸的是,这只会使命令窗口保持打开状态并阻止 Qt Gui 运行。它也只运行一次命令。循环时,它只是在第一个关闭时打开一个新的 cmd。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 2013-08-01
  • 2011-10-26
  • 2017-06-20
相关资源
最近更新 更多