Pregunta

I'm having issues converting a string to a double and not exactly sure what's wrong. My add function:

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;
}

Here is my open fuse function portion:

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);
       }
   }

so I tried cat test/add/1/2 and get a result of 0.00 and in my debugger I'm getting:

 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

So inside the add function the first printf is showing the string "1" and "2" correctly but when I try to convert it using strtod() or atof() , it converts my strings into 0.000000 and 0.000000. Any ideas?

¿Fue útil?

Solución 2

Something was wrong with the buffer so I used a string copy to fix the issue.

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;
}

Otros consejos

Probably you missed the includes:

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

What is wrong with usage of atof function?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top