Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ASCII string to int/float/long

Tags:

c

I have this code to convert an ASCII string to and int, float, or double. However, it prints "42" for all of them. Where did I go 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;
}
like image 498
user3897320 Avatar asked Feb 13 '23 08:02

user3897320


2 Answers

First, you should avoid use of the ato* functions (ie: atoi, atof, etc), because there are cases where the conversion failed, and it just returns zero, so you have no way to know if the input was really a string representing zero, or if it was due to a processing error. If you modify the example below, for example, and change buf2 to "z16", you will get a warning you can handle. atoi would not let you know about that error.

Second, your format specifiers are incorrect in your printf call. Your compiler should have generated warnings about this.

Please refer to the example below for a working version that includes conversion error handling. Not that the explicit casting of strtol to (int) in my example does allow for a potential integer overflow. Try making buf1 a large number, and see what happens.

Good luck!

Code Listing


#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;
}
like image 109
Cloud Avatar answered Feb 15 '23 12:02

Cloud


Change

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

to

printf("%d\t%ld\t%f\n", i, l, d);
like image 31
Raghu Srikanth Reddy Avatar answered Feb 15 '23 10:02

Raghu Srikanth Reddy