Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a C++ program in another C++ program?

Tags:

c++

linux

I have a simple C++ program that takes in inputs and outputs some string. Like this:

$ ./game
$ what kind of game? type r for regular, s for special.
$ r
$ choose a number from 1 - 10
$ 1
$ no try again
$ 2
$ no try again
$ 5
$ yes you WIN!

Now I want to write a c++ program can runs this c++ program and plays the game automatically without user input and then outputs it to a file or standard output.

Running it would look like this:

./program game r > outputfile

game is the game program, r for playing regular style.

How should I do this? The main reason I need this program is that I want to do automatic testing for a much bigger program.

like image 890
Mark Avatar asked Feb 24 '23 12:02

Mark


1 Answers

You could use std::system from <cstdlib>:

std::system("game r > outputfile");

The return value is ./program's, the sole argument must be of type char const *.

There is no standard way to run a program and feed it standard input, though. Judging by your command line, you're on some Unix variant where popen from <stdio.h> should work:

FILE *sub = popen("game r > outputfile", "w");

then write to sub with the stdio functions and read outputfile afterwards.

(But for simple testing, I'd recommend implementing the core logic of your program as a set of functions/classes that can be run by a custom main function in a loop; or pick your favorite scripting language to handle this kind of thing.)

like image 91
Fred Foo Avatar answered Feb 26 '23 21:02

Fred Foo