Do while循环在用户输入正确密码后仍持续执行问题求助
问题根因
- 核心问题是密码输入计数变量
i的初始化位置错误,被定义在了外层循环外部,不会随每次密码输入重置:- 第一次输入错误密码后,
i会保留上一次输入的字符长度,后续输入密码时新字符会从i当前位置开始写入,password数组前半段残留上一次输入的内容,导致strcmp对比永远不相等,无法跳出外层循环。 - 首次输入正确密码时的两次回车问题,是因为部分环境下
getch读取回车会依次返回\r(13)和\n(10),你的代码仅判断了ENTER=13作为输入终止,导致单次回车未被正常识别。
- 第一次输入错误密码后,
修复方案
- 每次触发重新输入密码前,手动将计数变量
i重置为0 - 优化回车判断逻辑,兼容
\r和\n两种回车返回值 - 补充缺失的
conio.h头文件引入(getch属于非标准库函数,定义在conio.h中,多数编译器需要引入才能正常编译)
修复后代码
#define ENTER 13 #define NEWLINE 10 #define TAB 9 #define BKSP 8 #define SPACE 32 #define PASSWORD "HelloWorld" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> // 补充getch依赖的头文件 int main(){ char password[100]; char ch; int i; do { printf("\n\n\t\t\t\t\tPlease enter your password: "); i = 0; // 每次输入密码前重置计数 while (1) { ch = getch(); if (ch == ENTER || ch == NEWLINE) { // 兼容两种回车格式 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; }
内容的提问来源于stack exchange,提问作者SimTim124
相关产品推荐
相关产品推荐

