system() and newlines

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>

using namespace 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?
You could make a list of strings and loop through them
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.

For this simple example I could do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "stdafx.h"
#include <string>
#include <windows.h>

using namespace 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).
Thats exactly what a list is for, there are lots of tutorials about lists and all kinds of classes you could use for this

http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
http://www.cprogramming.com/tutorial/stl/stllist.html
Hmmm... interesting. I have never used vectors or lists. Thank you very much for the links. I will read through them and give them a try.
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
1
2
1
2
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?
With a list you can easily add or remove a line wherever you like

but if you dont need to do that then dserbias solution is probably the easiest way
Last edited on
Topic archived. No new replies allowed.