我在将字符串转换为双精度时遇到问题,并且不确定出了什么问题。我的添加功能:
int add(const char *a,const char *b,char* str,int length)
{
printf("\n*you are in add function %s,%s*\n",a,b);
//double aa = strtod(a,NULL);
double aa =atof(a);
//double bb = strtod(b,NULL);
double bb = atof(b);
printf("\n after converting you get %f ,%f \n",aa,bb);
double c;
c= aa+bb;
//snprintf(str,length,"%.2f\n",c);
sprintf(str,"%.2f\n",c);
printf("\nthis is your new char %s\n",str);
return 0;
}
这是我的打开保险丝功能部分:
else if((strcmp(mytokens.toks[0],"add")) ==0 && (strcmp(mytokens.toks[1],"doc") != 0))
{
printf("\n You are in the ADD function and are trying to pass in %s,%s \n",mytokens.toks[1],mytokens.toks[2]);
char str[1024];
add(mytokens.toks[1],mytokens.toks[2],str,1024);
printf("\n This is the str after add %s \n",str);
len = strlen(str);
if (offset < len) {
if (offset + size > len)
size = len - offset;
printf("\nthis is for memcpy str %s",str);
memcpy(buf, str + offset, size);
}
}
所以我尝试cat test/add/1/2
得到一个结果,0.00
在我的调试器中我得到:
You are in the ADD function and are trying to pass in 1,2
*you are in add function 1,2*
after converting you get 0.000000 ,0.000000
this is your new char 0.00
This is the str after add 0.00
this is for memcpy str 0.00
因此,在 add 函数中,第一个 printf 正确显示了字符串“1”和“2”,但是当我尝试使用strtod()
or对其进行转换时atof()
,它会将我的字符串转换为 0.000000 和 0.000000。有任何想法吗?