user3897320
user3897320

Reputation: 87

Convert ASCII string to int/float/long

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

Upvotes: 4

Views: 22760

Answers (3)

ani627
ani627

Reputation: 6057

Please don't use ato* functions as ato* functions has been deprecated by strto* and should not be used in new code.

The problem with ato* is, if the converted value is out of range it causes undefined behavior.

For more information check here.

Upvotes: 1

Raghu Srikanth Reddy
Raghu Srikanth Reddy

Reputation: 2711

Change

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

to

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

Upvotes: 2

Cloud
Cloud

Reputation: 19333

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

Upvotes: 5

Related Questions