Create your own function to convert string to integer - C String

C examples for String:String Function

Description

Create your own function to convert string to integer

Demo Code

#include <stdio.h>
/* atoi:  convert s to integer */
int atoi(char s[])
{
    int i, n;// w  w w  .  ja va2s. com

    n = 0;
    for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i)
        n = 10 * n + (s[i] - '0');
    return n;
}

int main(){
    char buf[100];
    int n1, n2;

    while (fgets(buf, sizeof buf, stdin) != NULL) {
        sscanf(buf, "%d", &n1);
        n2 = atoi(buf);
        if (n1 != n2)
            printf("error %d %d\n", n1, n2);
    }
    return 0;
}

Result


Related Tutorials