簡體   English   中英

如何在我的簡單 C 程序中修復這個奇怪的錯誤?

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

您的代碼有幾個問題,包括:

  • 您不會將 C 字符串與“==”進行比較。 您必須改用strcmp() (或等效的)。
  • 小字符數組和“scanf()”的不安全使用的組合很可能導致緩沖區溢出。 您應該定義一個更大的緩沖區,並改用像fgets()這樣的“更安全”的方法。

建議的更改:

#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;
}
  1. 要比較兩個字符串,您可以使用strcmp()函數。 這將逐個字符地比較兩個字符串。 不要忘記使用頭文件string.h不能使用等號來比較兩個字符串,因為字符串文字是相同的,而 C 中的字符串是一個字符數組,它指的是一個地址。 所以如果你使用“==”符號,你最終會比較兩個地址。

  2. 盡管上述錯誤已得到糾正,但您仍會得到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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM