catoi

atoi function in ctype library not working in C


I almost read all of the articles about my problem in stackoverflow but they didn't solve it. I want a program that sums all the numbers in a string and shows me result. For example, when I write "a2s23l", it shows me 2 + 2 + 3 = 7 on screen. I wrote this:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main() {
    char input[15];
    printf("Write smth: ");
    gets(input);

    int i, result = 0;
    for(i=0; i<=15; i++)
    {
        if(isdigit(input[i]) != 0)
        {
            result = result + atoi(input[i]);
        }
    }

    printf("Your result: %d", result);

    return 0;
}

this is not working. I think there's something wrong about atoi function. Can you guys help me about this?


Solution

  • atoi(input[i]) is a problem as int atoi(const char *) expects a const char * and input[i] is a char.

    This implies OP did not have all compiler warnings enabled.
    Save time, enable all compiler warnings.

    Since input[i] is a digit character, to convert to a digit value:

    int single_digit_value = input[i] - '0';
    result = result + single_digit_value;
    

    Overrun

    for(i=0; i<=15; i++) may iterate past the end of the string. Instead look for the null character.

    // for(i=0; i<=15; i++)
    for(i=0; input[i]; i++)
    

    Evil gets()

    Why is the gets function so dangerous that it should not be used?.