繁体   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