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.
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) {