我是C的初学者。我有一个使用system("subprogram.exe")
函数运行另一个简单添加程序的程序。现在这个子程序得到两个整数输入,如何从主程序中为subprogram.c
文件提供输入。
主程序:
#include<stdio.h>
int main()
{
int a,b;
a=10;
b=10;
system("subprogram.exe");
}
现在子程序有以下代码..
#include<stdio.h>
int main()
{
int a,b,c;
c=a+b;
printf("%d",c);
return 0;
}
如何将“a”和“b”中的值从“主程序”复制到“子程序”?
答案 0 :(得分:1)
简单的答案命令行参数。
您的主要计划:
#include<stdio.h>
#include<string.h>
int main()
{
int a,b;
a=10;
b=10;
char str1[10], str2[10];
char progCmdline[100];
sprintf(str1, " %d", a); //Convert int a to string str1
sprintf(str2, " %d", b); //Convert int b to string str2
strcpy(progCmdline,"subprogram.exe "); //Build
strcat (progCmdline,str1); // Your command line string
strcat (prog,str2); // with inputs
system(progCmdline);
}
您的子程序:
#include<stdio.h>
int main(int argc, char **argv )
{
int a,b,c;
if(argc>0)
{
a = atoi(argv[1]);
b = atoi(argv[2]);
c = a + b;
printf("%d",c);
}
return 0;
}
subprogram.exe
为argv[0]
,2
为argv[1]
,3
为argv[2]
。阅读atoi参考,了解它的作用。
答案 1 :(得分:1)
您需要使用的是命令行参数,以简单地完成此操作。还有其他方法,如进程间通信,但如果要从主程序打开subprogram.exe,则可以使用命令行参数。
而不是
system("subprogram.exe");
使用
sprintf(command, "subprogram.exe %d %d", a, b)
system( command );
这会将整数与subprogram.exe连接起来,然后执行它。不要忘记声明命令字符数组。
但是,您还必须更改子程序main函数以获取参数。在执行程序时传递命令行参数时,参数数量和参数数组将传递给main函数。
int main ( int argc, char *argv[] )
{
if (argc < 2) /* assuming that you need two inputs */
{
printf("needs atleast two inputs");
}
else
{
printf("%d",atoi(argv[1])+argv[2]));
}
}
答案 2 :(得分:0)
您将拥有任何Inter Process Programming构造。您可以使用管道,消息队列或共享内存。您可以参考:http://www.cs.cf.ac.uk/Dave/C/node23.html
答案 3 :(得分:0)
你有2种方法,
将值作为命令行参数传递。这很简单。 你的主程序应该是 -
int main()
{
int a,b;
a=10;
b=10;
char str[50];
sprintf(str, "subprogram.exe %d %d", a, b);
system(str);
}
和subprogram.c -
include<stdio.h>
int main(int argc, char *argv[])
{
int a,b,c;
if(argc<3){
printf("not enough arguments");
exit();
}
a = atoi(argv[1]);
b = atoi(argv[2]);
c=a+b;
printf("%d",c);
return 0;
}
答案 4 :(得分:0)
或者,您可以将主程序保存到文件中,然后由子程序读取。
//In main program:
FILE * jakethedog = fopen("jakethedogfile.txt","w");
fprintf(jakethedog, "%d %d",a,b);
fclose(jakethedog);
//In subprogram:
FILE * cakethecat = fopen("jakethedogfile.txt","r");
fscanf(cakethecat,"%d %d",&a,&b);
fclose(cakethecat);
如果您想在两个方向上在主程序和子程序之间交换信息,我会发现这更有用。
答案 5 :(得分:0)
简单地说就是这样:
#include<stdio.h>
#include <process.h>
int main()
{
char command[100];
int a,b;
a=10;
b=10;
sprintf(command, "subprogram %i %i" , a,b);
system(command);
}
#include<stdio.h>
int main(int argc, char** argv)
{
int a,b,c;
a = atoi(argv[1]); // atoi() converts command line string type arrgument to int
b = atoi(argv[2]);
c=a+b;
printf("%d",c);
return 0;
}
atoi:如何将字符串转换为int类型
command line arguments:如何传递和使用命令行参数