Thread: Sum of octals found in input

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Oct 2020
    Posts
    69

    Sum of octals found in input

    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.
    Code:
    /* 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;
      }
    Input: John has 033 apples and 02 strawberries
    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?
    Last edited by rmmstn; 11-26-2020 at 07:03 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 07-22-2020, 05:17 PM
  2. comparing octals???
    By TaiL in forum C Programming
    Replies: 1
    Last Post: 10-13-2009, 12:55 PM
  3. Pq - Sq - Kq --- Found!!!
    By sean in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 12-02-2002, 07:07 PM
  4. Look what I found!
    By face_master in forum A Brief History of Cprogramming.com
    Replies: 4
    Last Post: 10-14-2002, 05:34 AM
  5. -lqt not found?
    By f0d in forum Linux Programming
    Replies: 2
    Last Post: 06-03-2002, 10:17 AM

Tags for this Thread