Convert ASCII string to int / float / long

I have this code to convert ASCII strings and int, float or double. However, he prints "42" for all of them. Where am I wrong? The syntax looks correct, no warnings.

#include <stdlib.h>
int main(void)
{
     char *buf1 = "42";
     char buf2[] = "69.00";
     int i;
     double d;
     long l;
     i = atoi(buf1);
     l = atol(buf1);
     d = atof(buf2);
     printf("%d\t%d\t%d\n", i, l, d);
     return 0;
}
+4
source share
3 answers

-, ato* (..: atoi, atof ..), , , , , , , . , , buf2 "z16", , . atoi .

-, printf. .

, , . , strtol (int) . buf1 , .

!


#include <stdio.h>   /* printf */
#include <stdlib.h>  /* strtox */
#include <errno.h>   /* error numbers */

#define BASE         (10)  /* use decimal */

int main(void) {
   char* errCheck;
   char *buf1   = "42";
   char *buf2   = "16";
   char  buf3[] = "69.00";
   int i;
   double d;
   long l;

   /* Handle conversions and handle errors */
   i = (int)strtol(buf1, &errCheck, BASE);
   if(errCheck == buf1) {
      printf("Conversion error:%s\n",buf1);
      return EIO;
   }
   l = strtol(buf2, &errCheck, BASE);
   if(errCheck == buf2) {
      printf("Conversion error:%s\n",buf2);
      return EIO;
   }
   d = strtod(buf3, &errCheck);
   if(errCheck == buf3) {
      printf("Conversion error:%s\n",buf3);
      return EIO;
   }

   printf("%d\t%ld\t%lf\n", i, l, d);
   return 0;
}
+4

printf("%d\t%d\t%d\n", i, l, d);

printf("%d\t%ld\t%f\n", i, l, d);
+2

, ato*, ato* strto* .

ato* , , undefined.

For more information check here.

+1
source

All Articles