I want to write a code that gets a number with unknown number of digits (means it can both 100 and 1000000). I thought of using getchar
and wrote the following code:
#include <stdio.h>
int main()
{
char nextdigit;
int finalnumber=0;
nextdigit=getchar();
while(nextdigit!='\n')
{
finalnumber=finalnumer*10+(int)nextdigit;
nextdigit=getchar();
}
printf("%d",finalnumber);
}
but seems like when I enter for example 3
it prints 51 (maybe the ascii value of 3
) and in fact doesn't allow me to enter digits anymore. What am I doing wrong?