I am trying to read characters one at a time and convert them to int in a cumulative manner. If the user enters a character other than a number i start the whole process all over again.
When i run this code, the code below getchar()
gets executed only after i press the enter key instead of executing with every key press. In brief, instead of taking one character at a time, it takes a string terminated with enter as input and then reads one character at a time from the input string and executes the while loop.
I am pretty sure it has something to do with the \n
in the printf statements.
My c code:
char* input=malloc(0);
char c;
int count=0;
int a;
int b;
errno=0;
printf("\nEnter two numbers a and b\n");
while(1){
count++;
printf(":Count:%d",count);
c=getchar();
printf("\n::%c::\n",c);
if(c=='\n')
break;
input=realloc(input,count);
input[count-1]=c;
errno=0;
a=strtol(input,NULL,10);
printf("\nNUMber::%d\n",a);
if (errno == ERANGE && (a == LONG_MAX || a == LONG_MIN)){
printf("\nLets start over again and please try entering numbers only\n");
count=0;
input=realloc(input,0);
}
}