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