为了拥有一个文本字段,您需要一个 GUI。 GUI 不是 C++ 的固有部分,因此您必须使用一些 GUI 框架,例如 Qt。从理论上讲,您只能使用 WinAPI 来完成,但我想这会很痛苦。在我的示例中,我从控制台获取输入数字。
关于调用批处理和传递参数,很简单。只需调用进程cmd.exe /C {yourbatch}.bat {parameters}。请注意,您可以将输入数据作为命令行参数传递给批处理(也可以使用环境变量)。为了启动exe-file,你可以使用WinAPI的CreateProcess函数(我从this answer中抽取了样本)
获得输出有点困难。其中一种方法是使用管道捕获批处理的控制台输出流。 this 之类的东西...但是,简单地使用文件来传递任何数据要容易得多。
C++ 示例:
#include <stdio.h>
#include <windows.h>
int main() {
int n;
scanf("%d", &n); //read integer n from console
int *arr = new int[n]; //create array of 1..n integers
for (int i = 0; i < n; i++)
arr[i] = i + 1;
char cmd[1024] = "cmd.exe /C script.bat"; //base command line
for (int i = 0; i < n; i++) //add array elements as console parameters
sprintf(cmd, "%s %d", cmd, i);
STARTUPINFO info = {sizeof(info)}; //create cmd.exe process
PROCESS_INFORMATION processInfo;
if (CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &info, &processInfo)) {
WaitForSingleObject(processInfo.hProcess, INFINITE);
CloseHandle(processInfo.hProcess); //note that we wait for completition
CloseHandle(processInfo.hThread);
}
int sum;
FILE *f = fopen("sum.txt", "r"); //read sum from 'sum.txt'
fscanf(f, "%d", &sum);
fclose(f);
printf("Sum of 1..%d is %d\n", n, sum); //print the sum
return 0;
}
Sample Batch(必须在工作目录中命名为script.bat):
del sum.txt
set sum=0
for %%x in (%*) do ( //sum all the parameters
set /A sum+=%%~x
)
echo %sum% >sum.txt //write result to sum.txt