如何在另一个C ++程序中运行一个C ++程序? [英] How to run a C++ program in another C++ program?
问题描述
我有一个简单的C ++程序,它接受输入并输出一些字符串.像这样:
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!
现在我要编写一个c ++程序,可以运行该c ++程序并自动进行游戏,而无需用户输入,然后将其输出到文件或标准输出中.
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.
运行它看起来像这样:
./program game r > outputfile
game是游戏程序,r用于播放常规样式.
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.
推荐答案
您可以使用<cstdlib>
中的std::system
:
std::system("game r > outputfile");
返回值为./program
,唯一的参数必须为char const *
类型.
The return value is ./program
's, the sole argument must be of type char const *
.
但是,没有标准的方法来运行程序并向其提供标准输入.从命令行判断,您使用的是Unix变体,其中<stdio.h>
中的popen
应该可以工作:
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");
然后使用stdio
函数写入sub
,然后读取outputfile
.
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.)
这篇关于如何在另一个C ++程序中运行一个C ++程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!