我正在用 C 编程编写一个简单的代码。老实说,我有很长一段时间没有在其中编程。所以我想制作一个简单的程序来重新认识这种编程语言。
这是代码:
#include <stdio.h>
#include <string.h>
int main()
{
char email;
char temppass[64];
char pass[] = "password";
printf("Enter your email: \n");
scanf("%s", &email);
printf("Enter your password: \n");
scanf("%s" , &temppass);
if(strcmp(temppass, pass) == 0){
printf("This is the password");
}
else{
printf("You Failed!");
}
return 0;
}
尽管我遇到了一些无法解决的问题。第一个问题是它给了我一个警告:
strcmp2.c: In function ‘main’:
strcmp2.c:14:13: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[64]’ [-Wformat=]
scanf("%s" , &temppass);
~^ ~~~~~~~~~
我很清楚这个问题可能看起来与其他问题重复,但就我搜索和阅读所有问题和答案而言,没有一个可以帮助我,因为它们是不同的并且没有帮助我。
一开始我尝试用 fgets()
来解决这个问题作为输入函数。编译代码时,它没有给我警告或错误,但问题是 fgets
放一个 \n
输入末尾的新行字符。所以用户输入和我要比较的字符串不一样。我尝试在 char pass[]="password\n"
添加新行字符看看它是否能解决任何问题,但又失败了。
但是,当我运行它并输入请求的信息时,strcmp()
即使输入的密码相同,函数也不会成功比较两个字符串。
如果有人愿意帮助我,我真的很感谢你和你的宝贵时间。非常感谢提前:)
最佳答案
您的密码测试不起作用的原因与警告有关。当 temppass 被声明为数组时,它实际上是一个指向静态分配内存的指针。因此,当您获取它的地址时,您不再指向数组的开头,而是指向一个变量,该变量的值指向数组的开头。情况类似于这段代码:
char *c = malloc(42);
scanf("%s", &c);
如您所见,我们为 scanf
提供了 char **
,而不是 char *
。
正如其他人所指出的,email
变量可能也应该是一个数组,并且对 scanf
的调用也不应该在此时获取电子邮件地址。
此外,最好显式初始化变量并绑定(bind)输入。对于前者,如果您在没有优化的情况下进行编译,那么编译器可能已经将您的内存清零,但是当您进入生产代码时,未初始化的变量是危险的。同样,由于输入被放置到静态分配的数组中,因此应该告诉 scanf 限制它复制的字符数。
#include <stdio.h>
#include <string.h>
int main()
{
char email[64] = { 0 };
char temppass[64] = { 0 };
char pass[] = "password";
printf("Enter your email: \n");
int scanf_return_value = scanf("%63s", email);
if (scanf_return_value != 1) {
printf("Error parsing input!\n");
if (scanf_return_value == EOF) {
perror("scanf");
} else {
printf("scanf returned unexpected value %d", scanf_return_value);
}
}
printf("Enter your password: \n");
scanf_return_value = scanf("%63s" , temppass);
if (scanf_return_value != 1) {
printf("Error parsing input!\n");
if (scanf_return_value == EOF) {
perror("scanf");
} else {
printf("scanf returned unexpected value %d", scanf_return_value);
}
}
if(strcmp(temppass, pass) == 0) {
printf("This is the password");
}
else {
printf("You Failed!");
}
return 0;
}
关于c - 警告 : [-Wformat=] and strcmp() not comparing in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59802966/