将字符串转换为double并返回字符串

时间:2014-04-25 20:02:02

标签: c string fuse atof strtod

我在将字符串转换为double时遇到问题,并且不确定错误是什么。我的添加功能:

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显示字符串&#34; 1&#34;和&#34; 2&#34;正确但当我尝试使用strtod()atof()进行转换时,它会将我的字符串转换为0.000000和0.000000。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

可能你错过了包括:

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

What is wrong with usage of atof function?

答案 1 :(得分: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;
}
相关问题