C sprintf()命令不起作用
我试图编写一个c程序,从用户那里得到两个浮点数,然后用execv()命令调用另一个程序。但我做不到,因为我把float转换成char,或者我不知道为什么。 问题是execv()命令不起作用;输出必须是这样的 输入第一个数字:5C sprintf()命令不起作用,c,arrays,execv,C,Arrays,Execv,我试图编写一个c程序,从用户那里得到两个浮点数,然后用execv()命令调用另一个程序。但我做不到,因为我把float转换成char,或者我不知道为什么。 问题是execv()命令不起作用;输出必须是这样的 输入第一个数字:5输入第二个数字:7 5.000000+7.000000=12.000000父PID:9745子PID:9746现在可以工作了 但现在是这样 输入第一个数字:5输入第二个数字:7父PID:9753 childPID:9754现在可以工作了 我的第一个c程序sum.c #inc
输入第二个数字:7
5.000000+7.000000=12.000000
父PID:9745子PID:9746现在可以工作了 但现在是这样 输入第一个数字:5
输入第二个数字:7
父PID:9753 childPID:9754现在可以工作了 我的第一个c程序sum.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if(argc!=3)
printf("error...\n");
double a=atof(argv[1]);
double b=atof(argv[2]);
printf("%lf + %lf = %lf \n",a,b,a+b);
return 0;
}
#包括
#包括
#包括
int main(int argc,字符**argv){
如果(argc!=3)
printf(“错误…\n”);
双a=atof(argv[1]);
双b=atof(argv[2]);
printf(“%lf+%lf=%lf\n”,a、b、a+b);
返回0;
}
第二个程序是calculate.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
float x,y;
pid_t pid;
printf("Enter first num: ");
scanf("%f",&x);
printf("Enter second num: ");
scanf("%f",&y);
if((pid=fork())== -1)
{
printf("can not fork..\n");
exit(1);
}
if(pid==0) //child
{
pid=getpid();
char *temp[] = {NULL,NULL,NULL,NULL};
temp[0]="sum";
sprintf(*temp[1],"%f",x); //here I want to convert float number to char but it doesn't work
sprintf(*temp[2],"%f",y);
execv("sum",temp);
}
else
{
wait(NULL);
printf("parentPID: %d childPID: %d works now.\n", getpid(), pid);
}
return 0;
}
#包括
#包括
#包括
int main()
{
浮动x,y;
pid_t pid;
printf(“输入第一个数值:”);
scanf(“%f”、&x);
printf(“输入第二个数值:”);
扫描频率(“%f”和“y”);
如果((pid=fork())=-1)
{
printf(“不能分叉..\n”);
出口(1);
}
if(pid==0)//子级
{
pid=getpid();
char*temp[]={NULL,NULL,NULL,NULL};
温度[0]=“总和”;
sprintf(*temp[1],“%f”,x);//这里我想将浮点数转换为字符,但它不起作用
sprintf(*temp[2],“%f”,y);
execv(“总和”,临时);
}
其他的
{
等待(空);
printf(“父pid:%d子pid:%d现在可以工作了。\n”,getpid(),pid);
}
返回0;
}
您没有alloc
分配到temp[1]
和temp[2]
并在sprintf
中使用它们作为目标缓冲区,在sprint中使用不正确的*
您可以使用malloc
来分配此内存,或者使用上面示例中所示的其他字符串来初始化数组
根据以下评论: 在
sum.c
中,将以下代码行更改为:
if(argc!=3)
{
printf("error...\n");
return -1;
}
否则,它会导致未定义的行为
您没有alloc
分配到temp[1]
和temp[2]
并在sprintf
中使用它们作为目标缓冲区,在sprint中使用不正确的*
您可以使用malloc
来分配此内存,或者使用上面示例中所示的其他字符串来初始化数组
根据以下评论: 在
sum.c
中,将以下代码行更改为:
if(argc!=3)
{
printf("error...\n");
return -1;
}
否则,它会导致未定义的行为。什么是“我做不到”呢?实际问题是什么?请澄清,“我做不到”到底是什么意思?实际问题是什么?请澄清。@MohitJain先生,如果第一个代码是(argc!=3),请说明退出或返回声明的要求。否则,使用
argv[1]
等可能会导致UB。您会遇到什么错误?您是否已完成我建议的所有4项更改并正确地重新编译。我建议使用gcc-W-Wall-O2标志进行编译。@SouravGhosh谢谢您完成了。任何时候都可以随意编辑我的答案。谢谢@MohitJain,在Sourav Ghosh的评论之后,它现在可以工作了:)@MohitJain先生,请提及在第一个代码的情况下if(argc!=3)
的退出或返回声明的要求。否则,使用argv[1]
等可能会导致UB。您会遇到什么错误?您是否已完成我建议的所有4项更改并正确地重新编译。我建议使用gcc-W-Wall-O2标志进行编译。@SouravGhosh谢谢您完成了。任何时候都可以随意编辑我的答案。谢谢@MohitJain,在Sourav Ghosh的评论之后,它现在可以工作了:)