How to implement the atoi() function to extract numbers from a string in C

3 Answers

0 votes
#include <stdio.h>
 
#define SIZE 10

int my_atoi(char s[]);
 
int main(void)
{
    char s[SIZE] = "100";
    int n;

    n = my_atoi(s);
    printf("n = %d\n", n);

    return 0;
}

int my_atoi(char s[]) 
{ 
    int n = 0; 
    
    for (int i = 0; s[i] >= '0' && s[i] <= '9'; i++) 
         n = 10 * n + (s[i] - '0'); 
         
    return n; 
} 
  
/*
  
run:
  
n = 100

*/



 



answered Nov 5, 2015 by avibootz
0 votes
#include <stdio.h>
#include <ctype.h>
  
#define SIZE 30
 
int my_atoi(char s[]);
  
int main(void)
{
    char s[SIZE] = "  xy    100 abc ";
    int n;
 
    n = my_atoi(s);
    printf("n = %d\n", n);
 
    return 0;
}
 
int my_atoi(char s[]) 
{ 
    int i = 0, n = 0;
    
    while (s[i])
    {
        if (s[i] >= '0' && s[i] <= '9') 
            n = 10 * n + (s[i] - '0'); 
            
        i++;
    }
          
    return n; 
} 
   
/*
   
run:
   
n = 100
 
*/

 



answered Nov 6, 2015 by avibootz
0 votes
#include <stdio.h>
#include <ctype.h>
  
#define SIZE 30
 
int my_atoi(char s[]);
  
int main(void)
{
    char s[SIZE] = "-100";
    int n;
 
    n = my_atoi(s);
    printf("n = %d\n", n);
 
    return 0;
}
 
int my_atoi(char s[]) 
{ 
    int i = 0, n = 0, sign = 1;
    
    if (s[0] == '-')
    {
        sign = -1;  
        i++;  
    }
    while (s[i])
    {
        if (s[i] >= '0' && s[i] <= '9') 
            n = 10 * n + (s[i] - '0'); 
            
        i++;
    }
          
    return sign * n; 
} 
   
/*
   
run:
   
n = -100

*/

 



answered Nov 6, 2015 by avibootz

Related questions

1 answer 122 views
122 views asked Nov 24, 2023 by avibootz
1 answer 119 views
1 answer 113 views
113 views asked Jun 25, 2022 by avibootz
...