Question

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);     
        }
    }
Was it helpful?

Solution

That's because of the fact that getchar() is terminal io settings dependent. Since most terminals have line buffering enabled, it waits until you press enter. Using termios.h, you can disable that. getch() is windows-only.

Here is some code to do what getch() does in Linux.

#include <termios.h>

char getch(void) {
    /* get original settings */
    struct termios new, old;
    tcgetattr(0, &old);
    new = old;

    /* set new settings and flush out terminal */
    new.c_lflag &= ~ICANON;
    tcsetattr(0, TCSAFLUSH, &new);

    /* get char and reset terminal */
    char ch = getchar();
    tcsetattr(0, TCSAFLUSH, &old);

    return ch;
}

Also, why realloc(blah, 0)? Why not just free(blah)?. Also, malloc(0) is undefined behaviour. It can return NULL or give a unique pointer. Same with realloc(blah, 0).

OTHER TIPS

just use:

#include <stdlib.h>

char getch()
{
char c; // This function should return the keystroke

system("stty raw");    // Raw input - wait for only a single keystroke
system("stty -echo");  // Echo off

c = getchar();

system("stty cooked"); // Cooked input - reset
system("stty echo");   // Echo on - Reset

return c;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top