在用户正确输入后执行 while 循环继续循环

Do while loop continuing to loop after correct input from user

我的程序正在继续循环而不是中断循环。

输入错误密码后,程序会要求用户重新输入密码(这是应该的)。虽然,如果用户输入的密码正确,但在之前输入错误的密码后,程序会在应该跳出循环时继续要求他们重新输入密码。

如果用户在第一次尝试时输入正确的密码,我的程序将执行,尽管它会让用户点击回车键两次而不是一次。

我不知道哪里出了问题。感谢任何帮助。

#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] = '[=10=]';
              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;
}

最小的修复方法是将 int i = 0; 移动到 do {} 循环中,以便在每次错误密码时重置它:

do {
    int i = 0;
    printf("\n\n\t\t\t\t\tPlease enter your password: ");

由于您依赖固定大小的缓冲区,因此您还应该检查 i < 100。例如:

#define PASSWORD_MAX_LEN 99
char password[PASSWORD_MAX_LEN + 1];

...
while(i < PASSWORD__MAX_LEN) {
   ch = getch();
   if (ch == ENTER) {             
       break;
   }
   ...
}
password[i] = '[=11=]';
...