My program is continuing a loop instead of breaking out of it.
After entering the incorrect password, the program will ask the user to re-enter the password (as it should). Although, if the user enters the password correctly, after previously entering the incorrect password, the program will continue to ask them to re-enter the password when it should break out of the loop.
My program will execute if the user enters the correct password on first attempt, although it makes the user click the enter key twice instead of once.
I can't figure out what is wrong. Any help is appreciated.
#define ENTER 13
#define TAB 9
#define BKSP 8
#define SPACE 32
#define PASSWORD "HelloWorld"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char password[100];
char ch;
int i = 0;
do {
printf("\n\n\t\t\t\t\tPlease enter your password: ");
while (1) {
ch = getch();
if (ch == ENTER) {
password[i] = '\0';
break;
}
else if (ch == BKSP) {
if (i > 0) {
i--;
printf("\b \b");
}
}
else if (ch == TAB || ch == SPACE) {
continue;
}
else {
password[i] = ch;
i ;
printf("*");
}
}
} while((strcmp(password, PASSWORD) != 0));
return 0;
}
CodePudding user response:
The minimal fix would be to move the int i = 0;
into the do {}
loop so it's reset each each wrong password:
do {
int i = 0;
printf("\n\n\t\t\t\t\tPlease enter your password: ");
As you rely on a fixed sized buffer, you should also check that i < 100
. For example:
#define PASSWORD_MAX_LEN 99
char password[PASSWORD_MAX_LEN 1];
...
while(i < PASSWORD__MAX_LEN) {
ch = getch();
if (ch == ENTER) {
break;
}
...
}
password[i] = '\0';
...