C++ Program to execute another Program with Command line arguments
Solution 1
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. Since the double quotes themselves need to be escaped inside a C++ string literal, what you need to write is
stream << "\"C:\\Tests\\SO Question\\bin\\Release\\HelloWorld.exe\""
<< " " // don't forget a space between the path and the arguments
<< "myargument";
Solution 2
This gives several warnings related to the backslashes
I believe \
is an escape character in C++ using \\
instead will probably solve this problem.
Stepan1010
Updated on July 09, 2022Comments
-
Stepan1010 almost 2 years
How do you execute a command line program with arguments from a c++ program? This is what I found online:
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.
ADDENDUM:
So based on Jon's answer the correct version for me looks like this:
#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; }