简体   繁体   English

使用命令行参数执行另一个程序的C ++程序

[英]C++ Program to execute another Program with Command line arguments

How do you execute a command line program with arguments from a c++ program? 如何使用c ++程序中的参数执行命令行程序? This is what I found online: 这是我在网上找到的:

http://www.cplusplus.com/forum/general/15794/ http://www.cplusplus.com/forum/general/15794/

std::stringstream stream;
stream <<"program.exe "<<cusip;
system(stream.str().c_str());

But it doesn't seem to accept an actual program location, so I am not sure how to apply this. 但它似乎不接受实际的程序位置,所以我不知道如何应用它。 My hope was to have something like this: 我希望有这样的事情:

std::stringstream stream;
stream <<"C:\Tests\SO Question\bin\Release\HelloWorld.exe "<<"myargument";
system(stream.str().c_str());

This gives several warnings related to the backslashes - and the program does not work. 这给出了与反斜杠相关的几个警告 - 程序不起作用。 Is it expecting you to have the program in some specific location? 是否希望您将程序放在某个特定位置?

This is the output I get in the console: 这是我在控制台中获得的输出:

'C:\\Tests' is not recognized as an internal or external command, operable program or batch file. “C:\\ Tests”不被识别为内部或外部命令,可操作程序或批处理文件。

ADDENDUM: 附录:

So based on Jon's answer the correct version for me looks like this: 所以根据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;
}

First of all, you should use double backslashes in literal strings whenever you want a single backslash to appear in the actual string value. 首先,只要您希望在实际字符串值中出现单个反斜杠,就应该在文字字符串中使用反斜杠。 This is according to the language grammar; 这是根据语言语法; a conforming compiler could do worse than simply warning about this. 一个符合标准的编译器可能比简单地警告这个更糟糕。

In any case, the problem you are experiencing is due to the fact that paths containing spaces must be enclosed in double quotes in Windows. 在任何情况下,您遇到的问题都是由于包含空格的路径必须用Windows中的双引号括起来。 Since the double quotes themselves need to be escaped inside a C++ string literal, what you need to write is 由于双引号本身需要在C ++字符串文字中进行转义,因此您需要编写的内容

stream << "\"C:\\Tests\\SO Question\\bin\\Release\\HelloWorld.exe\""
       << " " // don't forget a space between the path and the arguments
       << "myargument";

This gives several warnings related to the backslashes 这会给出与反斜杠相关的几个警告

I believe \\ is an escape character in C++ using \\\\ instead will probably solve this problem. 我相信\\是C ++中的转义字符使用\\\\而不是可能会解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM