[英]Program doesn't accept correct username and password after re-prompting the user to try again
一旦您输入了错误的用户名或密码,我的程序再次要求您输入,但发生这种情况时我的程序不接受正确的用户名或密码
我检查了该程序是否确实有效并且它确实接受了正确的用户名和密码,因此它让我感到困惑,为什么它在重新提示用户输入时没有。
另外,有什么方法可以改进我的密码屏蔽系统,使其不包括退格和输入?
谢谢!
#include <stdio.h>
#include <conio.h>
#include <string.h>
void login();
void mainmenu();
int main ()
{
login();
mainmenu();
return 0;
}
void login()
{
char username[100], password[100];
int i=0, logincheck=0;
printf("Welcome to The POS!");
while(logincheck != 1)
{
printf("\nPlease enter your username: ");
scanf("%s", username);
printf("\nPassword: ");
do
{
password[i] = getch();
printf("*");
i++;
}
while(password[i-1] != '\r');
password[i-1] = '\0';
if(strcmp(username, "username") == 0 && strcmp(password, "password") == 0)
{
printf("\nWelcome to the POS!");
logincheck = 1;
}
else
{
printf("\nIncorrect Username or Password!");
system("CLS");
}
}
}
void mainmenu()
{
printf("\n*Placeholder*");
}
您忘记在循环中重置计数器。
#include <stdio.h>
#include <conio.h>
#include <string.h>
void login();
void mainmenu();
int main ()
{
login();
mainmenu();
return 0;
}
void login()
{
char username[100], password[100];
int i, logincheck=0;
printf("Welcome to The POS!");
while(logincheck != 1)
{
i = 0; // Reset the counter
printf("\nPlease enter your username: ");
scanf("%s", username);
printf("\nPassword: ");
do
{
password[i] = getch();
// Added backspace handling
if (password[i] == '\b')
{
if (i > 0)
{
putchar('\b');
i--;
}
}
// Added return key handling
else if (password[i] == '\r' || password[i] == '\n')
{
i++;
break;
}
else
{
printf("*");
i++;
}
}
while(1);
password[i-1] = '\0';
if(strcmp(username, "username") == 0 && strcmp(password, "password") == 0)
{
printf("\nWelcome to the POS!");
logincheck = 1;
}
else
{
printf("\nIncorrect Username or Password!");
//system("CLS");
}
}
}
void mainmenu()
{
printf("\n*Placeholder*");
}
通过测试您的程序,您在重试用户/密码输入时遇到的问题是您没有将计数器“i”重置为零。 因此,您的程序只是继续将输入的字符添加到字符数组的末尾。 当我添加一些代码以重新初始化密码字符数组并添加代码行以将“i”的值重置为零时,验证在重试时起作用。
for (int j = 0; j < 100; j++)
{
password[j] = 0; /* This might be overkill, but this ensures that the character array does not have leftover characters */
}
i = 0;
printf("\nPassword: ");
do
{
password[i] = getch();
printf("*");
i++;
}
while(password[i-1] != '\r');
这是进行这些修订后的终端输出示例。
Incorrect Username or Password!
Please enter your username: username
Password: *********
Welcome to the POS!
*Placeholder*
希望能澄清事情。
问候。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.