【问题标题】:Do while loop continuing to loop after correct input from user在用户正确输入后执行while循环继续循环
【发布时间】:2021-10-28 01:54:45
【问题描述】:

我的程序继续循环而不是跳出它。

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

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

我不知道出了什么问题。任何帮助表示赞赏。

#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;
}

【问题讨论】:

  • 代码不完整。细节很重要。请提供完整的代码minimal reproducible example
  • 对于初学者,当密码错误时,您不会将 i 重置为 0。
  • 没有什么可以让您了解内部循环甚至测试密码!
  • @hesham_EE break; 怎么样?
  • @kaylum 哎呀......对!代码有一个中断。我错了,对不起!

标签: c loops while-loop


【解决方案1】:

最小的解决方法是将int i = 0; 移动到do {} 循环中,这样它就会重置每个错误的密码:

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

当您依赖固定大小的缓冲区时,您还应该检查i &lt; 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] = '\0';
...

【讨论】:

    猜你喜欢
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2015-07-26
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多