Online Courses
Free Tutorials  Go to Your University  Placement Preparation 
Goeduhub's Online Courses @ Udemy in Just INR 570/-
Online Training - Youtube Live Class Link
0 like 0 dislike
325 views
in Tutorial & Interview questions by Goeduhub's Expert (8.3k points)

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

Goeduhub's Top Online Courses @Udemy

For Indian Students- INR 360/- || For International Students- $9.99/-

S.No.

Course Name

 Coupon

1.

Tensorflow 2 & Keras:Deep Learning & Artificial Intelligence

Apply Coupon

2.

Natural Language Processing-NLP with Deep Learning in Python Apply Coupon

3.

Computer Vision OpenCV Python | YOLO| Deep Learning in Colab Apply Coupon
    More Courses

1 Answer

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

3.3k questions

7.1k answers

394 comments

4.6k users

Related questions

0 like 0 dislike
1 answer 319 views
0 like 0 dislike
1 answer 144 views
0 like 0 dislike
1 answer 181 views

 Goeduhub:

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