C program: keyboard does not recognise enter using getch()

213 Views Asked by At

So I'm trying to mask my password with '*'. So far this code works with backspace and all. However, when I hit enter, it doesn't do anything at all and thus, I couldn't move on with the program.

This is what I have so far:

    printf("Password:");

    fflush(stdout);
    while((ch=mygetch()) != EOF || ch != 13 || z<sizeof(password)-1){
            if(ch==127 && z>0){
                    printf("\b \b"); fflush(stdout);
                    z--; password[z] = '\0';
            }
            else if(isalnum(ch)){
                    putchar('*');
                    password[z++] = (char)ch;
            }
    }
    password[z] = '\0';
    printf("password: %s", password);

And I have mygetch defined on this function:

    int mygetch(){
        int ch;
        struct termios oldt, newt;

        tcgetattr (STDIN_FILENO, &oldt);
        newt=oldt;
        newt.c_lflag &= ~(ICANON | ECHO);
        tcsetattr (STDIN_FILENO, TCSANOW, &newt);
        ch = getchar();
        tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

        return ch;
    }

I tried putting an if-statement inside, that if(ch==13) break;, it will break the while-loop. However, it still didn't do anything. Keyboard still couldn't recognize the enter key. It would just do nothing.

If I replace all || with &&, it will immediately exit the program.

2

There are 2 best solutions below

1
On BEST ANSWER

It seems that the newline is assumed CR (= 13). But it can be LF (= 10). Please try to add one more condition to the while loop:

while((ch=mygetch()) != EOF || ch != 10 || ch != 13 || z<sizeof(password)-1) {
0
On

Use &&, and add LF condition

while((ch=mygetch()) != EOF && ch != 13 && ch != 10 && z<sizeof(password)-1){