Hi,
I need to read unsigned integer and I want to read it number by number. I did this function. But it has "one bug". It can't read number like 4 294 967 295. Max what it reads is like 4 294 967 29. It's because I multiplied it by ten and then divided by 10 at end of function.
I didn't figured any other way of programming this function.
I don't want to use scanf or any other function. I need to scan it number by number because if it's bigger than ULONG_MAX it will stop getting another number. Than it will calculate some my other things.
All I want is some hint how to read number like 4 294 967 295 (32-bit ULONG_MAX) number by number using getchar(). Eventually some hint how to recognize "overflow" or how it's named when using unsigned integer.
This code is pretty lame, I didn't do any test if I am reading numbers from stdin, etc. It's not on my task list at this time.
#include <stdio.h>
unsigned long int readNumbersByGetchar()
{
unsigned long int thisNumber = 0, i = 0;
while ((i = getchar()) != '\n') /*I am reading it until end of line*/
{
thisNumber *= 10; /*At the start I multiply it by 10, at first passage it's 0x10*/
i = (i - 48); /*Because of definition of ASCII code, ASCII 48 == 0*/
thisNumber += (i*10); /*I multiply read number by 10 and than I add it to variable thisNumber
*which was multiplied by 10 before*/
}
thisNumber /= 10; /*At end of reading whole number from stdin I divide it by 10*/
printf("%lu", thisNumber); /*Just for my testing*/
return thisNumber; /*Return thisNumber to function*/
}