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

>>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.