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