FIFA-2022 Career Guide Free Tutorials Go to Your University Placement Preparation 
0 like 0 dislike
631 views
in Tutorial & Interview questions by Goeduhub's Expert (9.3k points)

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

1 Answer

0 like 0 dislike
by Goeduhub's Expert (9.3k 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(). 

Learn & Improve In-Demand Data Skills Online in this Summer With  These High Quality Courses[Recommended by GOEDUHUB]:-

Best Data Science Online Courses[Lists] on:-

Claim your 10 Days FREE Trial for Pluralsight.

Best Data Science Courses on Datacamp
Best Data Science Courses on Coursera
Best Data Science Courses on Udemy
Best Data Science Courses on Pluralsight
Best Data Science Courses & Microdegrees on Udacity
Best Artificial Intelligence[AI] Courses on Coursera
Best Machine Learning[ML] Courses on Coursera
Best Python Programming Courses on Coursera
Best Artificial Intelligence[AI] Courses on Udemy
Best Python Programming Courses on Udemy

Related questions

0 like 0 dislike
1 answer 773 views
0 like 0 dislike
1 answer 291 views
0 like 0 dislike
1 answer 419 views

 Important Lists:

Important Lists, Exams & Cutoffs Exams after Graduation PSUs

 Goeduhub:

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

 

Free Online Directory

...