简体   繁体   中英

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?

atoi(input[i]) is a problem as atoi() expects a 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM