【发布时间】:2013-01-27 02:58:42
【问题描述】:
如何使用来自 c++ 程序的参数执行命令行程序?这是我在网上找到的:
http://www.cplusplus.com/forum/general/15794/
std::stringstream stream;
stream <<"program.exe "<<cusip;
system(stream.str().c_str());
但它似乎不接受实际的程序位置,所以我不确定如何应用它。我希望有这样的东西:
std::stringstream stream;
stream <<"C:\Tests\SO Question\bin\Release\HelloWorld.exe "<<"myargument";
system(stream.str().c_str());
这会给出几个与反斜杠相关的警告 - 并且程序无法运行。是否希望您将程序放在某个特定位置?
这是我在控制台中得到的输出:
'C:\Tests' 未被识别为内部或外部命令, 可运行的程序或批处理文件。
附录:
因此,根据 Jon 的回答,我的正确版本如下所示:
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <cstring>
int main(int argc, char *argv[])
{
std::stringstream stream;
stream << "\"C:\\Tests\\SO Question\\bin\\Release\\HelloWorld.exe\""
<< " " // don't forget a space between the path and the arguments
<< "myargument";
system(stream.str().c_str());
return 0;
}
【问题讨论】:
-
知道如何将标准输出从 system(...) 重定向到 std::string 或 std::stringstream?
-
@Pupsik 系统函数返回一个 int。显然,您需要知道您使用的任何操作系统的状态代码:“如果 command 不是空指针,则返回的值取决于系统和库实现,但通常预计是由调用命令,如果支持的话。” - 来自cplusplus.com/reference/cstdlib/system - 然后您可以根据返回的 int 生成正确的错误消息。
-
@Pupsik 不,我正在和其他 Pupsik 交谈。约翰尼·普普西克。他来自爱尔兰。
-
PS:C++ 实际上有一个
+运算符用于连接字符串 - 示例 v.1:string myString = "something"; myString += "something else";或 v.2:直接但使用类型转换string my = (string)"something" + " " +"something else";要点是: i> 您不必为此使用其他库... -
在这样的程序中,您可能希望返回退出值
HelloWorld.exe,而不是零。也就是说,将最后两条语句替换为:return system(stream.str().c_str());
标签: c++ command-line command command-line-arguments