[英]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.