Sum a CSV Line

Lab C Intermediate 20 points

Read a line of comma-separated integers (possibly negative) and print their count and sum, parsing digits yourself.

Input

One line.

Output

count sum

Example

Input

10,20,-5,7

Output

4 32
Sample input available Sample output available
Editor
C

Hints

Build each number digit by digit: value = value * 10 + digit.

Finish a number when you hit a comma or the end.

Solution explanation

This is what atoi does internally, extended to handle a list.

Show solution
#include <stdio.h>

int main() {
    char s[300];
    fgets(s, 300, stdin);
    int count = 0, sum = 0, value = 0, sign = 1, in_number = 0;
    for (int i = 0; ; i++) {
        char c = s[i];
        if (c == '-') {
            sign = -1;
        } else if (c >= '0' && c <= '9') {
            value = value * 10 + (c - '0');
            in_number = 1;
        } else {
            if (in_number) {
                sum += sign * value;
                count++;
            }
            value = 0;
            sign = 1;
            in_number = 0;
            if (c == '\0' || c == '\n') break;
        }
    }
    printf("%d %d\n", count, sum);
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD