Hello

Im trying to learn C rfrom the C book.

Now I have this exercise :

Write a function that returns an integer: the decimal value of a string of digits that it reads using getchar. For example, if it reads 1 followed by 4 followed by 6, it will return the number 146. You may make the assumption that the digits 0–9 are consecutive in the computer's representation (the Standard says so) and that the function will only have to deal with valid digits and newline, so error checking is not needed.

I looked at the answer but it seems unlogical for me.
The answer the book gave was this :

#include <stdio.h>
#include <stdlib.h>

main(){
   printf("Type in a string: ");
   printf("The value was: %d\n", getnum());
   exit(EXIT_SUCCESS);
}

getnum(){
   int c, value;;

   value = 0;
   c = getchar();
   while(c != '\n'){
      value = 10*value + c - '0';
      c = getchar();
   }
   return (value);

Let's try to dry run it.
Let says the first input is 1

Then c= 49
Then value would be value = value *10 + c - "0"
So value would be 0*10 + 49 - "0" = 490

Then output is 2
C= 50
Value would be 490 * 10 + 50 - "0" = 4950

Then output would be a and the loop stops.
Then
printf("The value was: %d\n", getnum());
So it would print a digital which was the outcome of getnum() so it would be 4950 instead of 12

IM a thinking wrong or is the solution of the book wrong ?

Roelof

Dani AI

Generated

Clarification for : the math in the book is correct — the mistake was interpreting '0' as the string "0". In C a character literal like '0' has an integer code (48 in ASCII). getchar() returns the code for a typed character (for '1' that is 49). Subtracting '0' converts the character digit into its numeric value, so c - '0' yields 1 for '1', 2 for '2', etc. As and pointed out, that subtraction is what makes value = value * 10 + (c - '0') accumulate the decimal value correctly.

A simple dry run (conceptual): start with value = 0. Read '1' (49): value = 0*10 + (49 - 48) = 1. Read '4' (52): value = 1*10 + (52 - 48) = 14. Repeating this produces the expected integer.

A slightly more robust form of getnum (addresses EOF, non-digit chars and overflow) might look like:

#include <stdio.h>
#include <limits.h>

int getnum(void) {
    int c;
    long value = 0;

    while ((c = getchar()) != '\n' && c != EOF) {
        if (c < '0' || c > '9') break; /* stop on non-digit */
        value = value * 10 + (c - '0');
        if (value > INT_MAX) return INT_MAX; /* simple overflow handling */
    }
    return (int)value;
}

Troubleshooting notes: prefer int for c because getchar() returns EOF as a distinct value; use single quotes for character literals ('0' not "0"); modern compilers warn about implicit declarations and other issues, so compile with warnings enabled (for example -Wall -Wextra) and fix any warnings. The book's printed solution had small syntax/formatting issues in the post, but the conversion logic itself is correct.

Recommended Answers

All 6 Replies

>>So value would be 0*10 + 49 - "0" = 490

Wrong. It's '0', not "0". Look up any ascii charact to see the numeric value of '0' is 48. Therefore the math is 0*10 + 49 - 48 = 1 . I don't know how you got 490.

You're neglecting to account for the subtraction of '0' (with an integer value of 48, in this case):

c = 49
0 * 10 == 0
0 + 49 == 49
49 - 48 == 1

Next character:

c = 50
1 * 10 == 10
10 + 50 == 60
60 - 48 == 12

IM a thinking wrong or is the solution of the book wrong ?

The code from your book is wrong, unless you've paraphrased it, but the solution is fine.

Oke,

Thanks for the explantion.
But what do you mean with the code of my book is wrong but the solution is allright

Roelof

I mean the code doesn't compile as posted, but if you fix the errors, it'll work as designed.

I mean the code doesn't compile as posted, but if you fix the errors, it'll work as designed.

ok thanks

I have a solution of it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.