此函式用于 C 語言的登錄系統。它可以正確啟動,并且根據語言語法看起來是正確的代碼。當我在輸入用戶名/密碼后嘗試打開檔案時,它回傳“錯誤,重試”訊息。該檔案是一個 .txt 檔案,有兩行,用戶名和密碼。
void login()
{
while (1)
{
printf("---- Bank Management ----\n\n");
printf("Please login...\n");
char username[25] = {'\0'};
printf("\nEnter username:\n");
fgets(username, sizeof(username), stdin);
int c = 0;
while (c = getchar() != '\n' && c != EOF);
char password[25] = {'\0'};
printf("\nEnter password:\n");
fgets(password, sizeof(password), stdin);
char extension[5] = ".txt";
char fileName[31] = {'\0'};
strcpy(fileName, username);
strcat(fileName, extension);
FILE *fp = fopen(fileName, "r");
if (fp != NULL)
{
char setUsername[5] = "bank";
char setPassword[5] = "temp";
char fileContents1[25] = {'\0'};
char fileContents2[25] = {'\0'};
for (int i = 0; i <= 2; i )
{
if (i == 1)
{
fgets(fileContents1, sizeof(fileContents1), fp);
if (i == 2)
{
fgets(fileContents2, sizeof(fileContents2), fp);
}
}
if ((strcmp(setUsername, fileContents1) != 0) && (strcmp(setPassword, fileContents2) != 0))
{
menu();
} else
{
printf("\nInvalid username or password, try again.\n\n");
continue;
}
}
} else
{
printf("\nError, try again.\n\n");
continue;
}
fclose(fp);
}
}
uj5u.com熱心網友回復:
不要將所有代碼都包含在 中if( fp != NULL ),而是檢查錯誤并立即退出。
FILE *fp = fopen(fileName, "r");
if( fp == NULL ) {
perror(fileName);
}
// Without a size, C will figure it out.
char setUsername[] = "bank";
char setPassword[] = "temp";
...
使用perror有原因的體面錯誤訊息。
myusername
.txt: No such file or directory.
哎呀,用戶名有換行符。
fgets讀取整行,包括換行符。該換行符必須被剝離。
這可能while (c = getchar() != '\n' && c != EOF);是試圖做的事情,但事實并非如此。它正在讀取輸入,直到看到換行符或檔案結尾......然后將輸入丟棄。這就是用戶在輸入用戶名后必須按兩次回車的原因。
fgets已經將用戶名從輸入讀取到記憶體中。我們可以撰寫一個小函式來跳轉到字串的最后一個字符并將換行符變為空。
void strip_newline(char *string) {
char *end = string strlen(string) - 1;
if( *end == '\n' ) {
*end = '\0';
}
}
或者我們可以使用scanf它,因為它會去除尾隨空格。
// "" is equivalent to {'\0'} and easier to understand.
char username[25] = "";
printf("\nEnter username:\n");
// Unlike fgets, scanf does not leave space for the null byte.
scanf("$s", username);
char password[25] = "";
printf("\nEnter password:\n");
scanf("$s", password);
通常scanf是要避免的,但是對于這種簡單的決議來說很好。
uj5u.com熱心網友回復:
關于:
fgets(...) statements.
讀取輸入時,'\n' 包含在讀取的資料中。
所以必須洗掉那個字符。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/405048.html
標籤:
