0

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?

Dragesia
  • 25
  • 6
  • 4
    The argument to `atoi` must be a string, not a `char`. – Barmar Nov 08 '21 at 22:30
  • 2
    You should have gotten a warning when you tried to compile `atoi(input[i])` – Barmar Nov 08 '21 at 22:30
  • 1
    Never describe a problem as “not working.” Always state what you observe and what you desire instead, as well as any input and conditions needed to reproduce the problem. E.g., say “When I try to compile this, my compiler prints the error message *text of error message*” or “This program compiles with a warning I ignored, but when it runs, it prints *exact text of output*, but I want it to print *exact desired text*.” – Eric Postpischil Nov 08 '21 at 22:32
  • 3
    You don't need to use `atoi()` to convert a single digit to a number. Just use `input[i] - '0'` – Barmar Nov 08 '21 at 22:35
  • @EricPostpischil i will pay attention next time, thank you. – Dragesia Nov 09 '21 at 21:16
  • @Barmar Yes, I understand that why atoi function didn't worked, but I don't understand why 'input[i] - '0'' is worked. – Dragesia Nov 09 '21 at 21:18
  • Because all the numeric character codes are sequential. – Barmar Nov 09 '21 at 21:20
  • See https://stackoverflow.com/questions/15598698/why-does-subtracting-0-in-c-result-in-the-number-that-the-char-is-representing – Barmar Nov 09 '21 at 21:20
  • @Barmar okay, thanks. – Dragesia Nov 09 '21 at 21:22

1 Answers1

3

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?.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256