I really want to understand character I/O in C but I feel like my understanding is faulty about certain concepts. I wanna write a program that gives me the sum of all base-8 numbers found in input, but the sum is never incremented.
Input: John has 033 apples and 02 strawberriesCode:/* Write a function that reads data from standard input until EOF is found and returns the sum of the base-8 numbers found into the input. We consider a number in base-8 a sequence that starts with 0 and is followed by digits from range [0-7]. The numbers must be separated from other words by at least one whitespace. All the numbers and the final sum are guaranteed to fit in "unsigned" data type. */ #include <stdio.h> int main(){ int current, last; unsigned sum=0; int n = 0; printf("Enter text:\n"); current = getchar(); while(current != '\n'){ putchar(current); last = current; current = getchar(); if(last == '0' && isdigit(current)){ last = current; current = getchar(); while(isdigit(current)){ n = current- '0'; sum = sum+n; } } } printf("\nThe sum is %d", sum); return 0; }
Output:
John has 033 apples and 02 strawberries
The sum is 0
Please bear in mind that, although I am familiar with strings, I shouldn't really use them for this solution (not that I'd know how to anyway). 'current' and 'last' are meant to define the current char and the last char from the input. I don't really understand how can I 'construct' my number from the characters, since I don't have to add them digit by digit but as whole numbers. Could you help me?