SUMMER TRAINING Free Tutorials  Go To Your University  Placement Preparation 

Project Based Best Summer Training Courses in Jaipur

0 like 0 dislike
139 views
in Tutorial & Interview questions by Goeduhub's Expert (8.1k points)

 Convert Strings to Number: atoi(), atof() (dangerous, don't use them)

1 Answer

0 like 0 dislike
by Goeduhub's Expert (8.1k points)
 
Best answer

Warning: The functions atoi, atol, atoll and atof are inherently unsafe, because: If the value of the result cannot be represented, the behavior is undefined. (7.20.1p1)

#include <stdio.h> 

#include <stdlib.h>

int main(int argc, char** argv) 

{    

int val;    

if (argc < 2)    

{

printf("Usage: %s <integer>\n", argv[0]);        

return 0;    

}

val = atoi(argv[1]);

printf("String value = %s, Int value = %d\n", argv[1], val);

return 0; 

}

When the string to be converted is a valid decimal integer that is in range, the function works:

$ ./atoi 100 String value = 100, Int value = 100 

$ ./atoi 200 String value = 200, Int value = 200

For strings that start with a number, followed by something else, only the initial number is parsed:

$ ./atoi 0x200 0 

$ ./atoi 0123x300 

123

In all other cases, the behavior is undefined:

$ ./atoi hello 

Formatting the hard disk...

Because of the ambiguities above and this undefined behavior, the atoi family of functions should never be used.

  1. To convert to long int, use strtol() instead of atol(). 
  2. To convert to double, use strtod() instead of atof().

Version ≥ C99 

  • To convert to long long int, use strtoll() instead of atoll(). 

Related questions

 Goeduhub:

About Us | Contact Us || Terms & Conditions | Privacy Policy || Youtube Channel || Telegram Channel © goeduhub.com Social::   |  | 
...