0

我在将字符串转换为双精度时遇到问题,并且不确定出了什么问题。我的添加功能:

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。有任何想法吗?

4

2 回答 2

2

可能你错过了包括:

#include <stdio.h>
#include <stdlib.h>

atof 函数的使用有什么问题?

于 2014-04-25T20:36:59.853 回答
0

缓冲区有问题,所以我使用字符串副本来解决问题。

int add(char *a,char *b,char* str,int length)
{
  char a1[100];
  char b1[100];
  strcpy(a1,a);
  strcpy(b1,b);
  printf("\n*you are in add function %s,%s*\n",a1,b1);
  double aa =atof(a1);
  double bb = atof(b1);
  printf("\n after converting you get %f ,%f \n",aa,bb);
  double c;
  c= aa+bb;
  snprintf(str,length,"%.2f\n",c);
  printf("\nthis is your new char %s\n",str);
  return 0;
}
于 2014-04-25T21:08:39.420 回答