0

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;
}
6
  • Code is incomplete. Details matter. Please provide complete code as a minimal reproducible example. Commented Oct 28, 2021 at 1:59
  • 1
    For starters you are not resetting i back to 0 when the password is wrong. Commented Oct 28, 2021 at 2:00
  • Nothing will ger you our of the inner loop to even test the password! Commented Oct 28, 2021 at 2:18
  • @hesham_EE How about break;? Commented Oct 28, 2021 at 2:23
  • @kaylum oops ... right! The code has a break. I'm wrong, sorry! Commented Oct 28, 2021 at 2:25

1 Answer 1

1

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';
...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.