我可以在系统()中使用两个字符串吗?

Can i use two strings in system()?

本文关键字:两个 字符串 系统 我可以      更新时间:2023-10-16

我正在尝试做这样的事情:

{
cout << "command: ";
cin >> m;
cout << "option: ";
cin >> o;
system(m+o);
}

以便用户可以选择要运行的命令和选项(如果需要)

system () 函数需要一个char *参数,你也忘记了空格分隔。你应该做这样的事情:

system(std::string(m + " " + o).c_str())

无论如何,我强烈建议您不要使用system ()功能,因为它是一个很大的安全漏洞。

有关这方面的更多详细信息,我建议您阅读以下帖子:

  • 为什么在 C 和 C++ 中应该避免使用 system() 函数?

您只能将参数传递给system()- 一个以空结尾的 C 样式字符串。但是,只要主机系统可以处理该命令,该字符串就可以包含任何复杂程度的命令。

例子:

system("ls");
system("ls -alF");
system("ls -alF | some-other-program ");

假设mo在发布的代码中属于std::string类型,您可能需要使用:

std::string command = m + " " + o;
system(command.c_str());