[英]How can fix this weird error in my simple C program?
這是一個出錯的簡單 C 身份驗證程序。 它從控制台讀取字符串作為用戶名和密碼作為輸入正確,但用戶名輸入已成為空格字符串。 可能是什么錯誤?
#include <stdio.h>
int main()
{
char username[4];
char password[8];
printf("Enter username: ");
scanf("%s", username);
printf("Enter password: ");
scanf("%s", password);
if (username == "ojas" && password == "ojas1234")
{
printf("Access granted!");
}
else
{
printf("%s and %s\n", username, password);
printf("Access denied");
}
return 0;
}
Enter username: ojas
Enter password: ojas1234
and ojas1234
Access denied
您的代碼有幾個問題,包括:
建議的更改:
#include <stdio.h>
#include <string.h>
#define MAX_STRING 80
int main()
{
char username[MAX_STRING];
char password[MAX_STRING];
printf("Enter username: ");
fgets(username, MAX_STRING, stdin);
strtok(username, "\n");
printf("Enter password: ");
fgets(password, MAX_STRING, stdin);
strtok(password, "\n");
if ((strcmp(username, "ojas") == 0) && (strcmp(password, "ojas1234") == 0)){
printf("Access granted!");
}
else {
printf("%s and %s\n", username, password);
printf("Access denied");
}
return 0;
}
要比較兩個字符串,您可以使用strcmp()
函數。 這將逐個字符地比較兩個字符串。 不要忘記使用頭文件string.h
不能使用等號來比較兩個字符串,因為字符串文字是相同的,而 C 中的字符串是一個字符數組,它指的是一個地址。 所以如果你使用“==”符號,你最終會比較兩個地址。
盡管上述錯誤已得到糾正,但您仍會得到Access Denied的輸出。 那是因為您的緩沖區溢出。 因此,為您的用戶名和密碼字符數組定義一個大數字。
下面的代碼可能會幫助您解決這些問題。
#include<stdio.h>
#include<string.h>
#define LEN 50
int main()
{
char username[LEN];
char password[LEN];
printf("Enter username: ");
scanf("%s", username);
printf("Enter password: ");
scanf("%s", password);
if ((strcmp(username,"ojas") == 0) && (strcmp(password,"ojas1234") == 0))
{
printf("Access granted!");
}
else
{
printf("%s and %s\n", username, password);
printf("Access denied");
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.