I am trying to have my c++ app use windows console commands. I currently, my program spools a bunch of commands, then outputs to a batch file, and finally my program executes the batch file via system("mybatch.bat"). I think this is really ugly and would like to execute the windoes commands directly without the use of the batch file.
I am stuck on how on the newlines, for instance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include "stdafx.h"
#include <string>
#include <windows.h>
usingnamespace std;
int main(void)
{
string test="echo This is a test"; //first command
test.append("\n"); //newline
test.append("echo This is a second test"); //second command
system(test.c_str()); //execute both commands
system("pause"); //pause
return 0;
}
produces the output:
This is a test
Press any key to continue...
but I expected
This is a test
This is a second test
Press any key to continue...
How can I have multiple commands in a single character array? I have tried \n, \r, and \n\r. I would prefer not to do system(command1); system(command2);. Any thoughts?
Obviously my actual program doesn't just output to the console. It should be as generalized as possible as the number of windows commands are unknown and have a wide range (1~500). I am not sure how I would keep a list of strings.
#include "stdafx.h"
#include <string>
#include <windows.h>
usingnamespace std;
int main(void)
{
string test[2];
int i=0,N=0;
test[N]="echo This is a test";
N++;
test[N]="echo This is a second test";
N++;
for(i;i<N;i++){
system(test[i].c_str()); //execute both commands
}
system("pause"); //pause
return 0;
}
and it produces the expected output. But I knew adhead of time the number of commands (2).
You could keep the starting approach, but the console will stop executing the commands when it encounters newlines. You can use '&' to separate them.
For example, if you have:
1 2
echo 1
echo 2
and you call it using system("...") you will get 1
But if you use echo 1 & echo 2
you will get
That works too. My actual program is written with the example's approach. Fixing the program would be as simple as replacing all my \n with &. Is there an advantage to using lists over the way I was doing it?