0

I was reading a book and this part confuses me a bit regarding getchar()

int peekchar(void){

        int c;
        c = getchar();
        if(c!=EOF) ungetc(c,stdin);
        return c;

}

int readNumber(void){

        int accumulator=0;     /*Number read so far*/
        int c;

     while((c = peekchar()) != EOF && isdigit(c)) {
     c = getchar();             /* consume it */
     accumulator *= 10;         /* shift previous digits over */
     accumulator += (c - '0');  /* add decimal value of new digit */
   }
return accumulator;
}

What exactly happens here in accumulator += (c - '0');

And the input would be digits i.e 123 would be given as input and that will be printed as output 123 again. This is what the program does. Any explanation would be helpful guys.

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
poda_badu
  • 159
  • 7
  • 2
    c and c++ are distinct languages. If your question is about c, it's not helpful to tag c++. – François Andrieux Nov 23 '17 at 15:52
  • sorry about that man :) – poda_badu Nov 23 '17 at 15:52
  • 1
    `c - '0'` will return the difference between the value of the character stored by `c` and the value of the character '`0`'. Since numerals have incremental values, (each numeral's character's value is 1 larger than the previous), that offset is equivalent to the value that character represents. For example, (`'4' - '0' == 4`). – François Andrieux Nov 23 '17 at 15:54

0 Answers0