convert a string to integer – atoi()

Home Forums C-programming.. convert a string to integer – atoi()

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #2128 Reply
    Humble
    Keymaster

    All reference for converting a string to integer point to use “atoi()” function.. how-ever please note that, it does not act like what you read above.. That said, if your string contains digits it will convert to integer ,BUT the string has to start with “digit”..

    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    
    //char str[]="a123";
    char str[]="12a123";
    
    printf ("%d", atoi(str));
    
    return 0;
    }
    
    
    You get "12" as an output here . How-ever if you enable the commented part (ie:char str[]="a123";) ,you will get "0" and not "12".
    
    atoi() is useful when taking integer arguments from the user.
    
    For additional reference, refer man page
    
    
    
    
    #2129 Reply
    Humble
    Keymaster

    If you are trying to convert the interger to string (opposite of what we discussed above) make use of sprintf() function as shown below:

    $ cat str.c 
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    
    char str[10];
    
    sprintf (str,"%d", 123);
    
    puts(str);
    
    return 0;
    }
    
    
    it will return 123 as an output..
    
Viewing 2 posts - 1 through 2 (of 2 total)
Reply To: convert a string to integer – atoi()
Your information: