我想做点什么,以防用户名等于"admin",但是当我输入用户名并通过时会出现此错误。
#include <stdio.h>
#include <stdlib.h>
int main() {
char UserName[100];
char admin[6]="admin";
double Password;
int choice,result;
while (choice!=3){
printf("Username : ");
scanf("%s",&UserName);
printf("Password : ");
scanf("%d",Password);
char admin=admin;
if(strcmp(UserName, admin)&&(Password==1234))
{
printf(" enter your choice : ");
}
}
return 0;
}
我试图尽量减少对代码的更改。查看我对可能有效(未经测试(替代方案的尝试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) { // full definition with prototype
char UserName[100];
char admin[6] = "admin";
int Password; // changed to int
int choice = 0, result; // initialize choice
while (choice != 3) {
printf("Username : ");
// limit input, the & is wrong, check the return value of scanf
if (scanf("%99s", UserName) != 1) exit(EXIT_FAILURE);
printf("Password : ");
// match type of "%" and variable, check the return value
if (scanf("%d", Password) != 1) exit(EXIT_FAILURE);
// char admin = admin; // deleted
// strcmp returns 0 when the strings match
if ((strcmp(UserName, admin) == 0) && (Password == 1234))
{
printf("OK!n"); // do something
}
// block structure messed up?
printf(" enter your choice : ");
if (scanf("%d", &choice) != 1) exit(EXIT_FAILURE);
}
return 0;
}
当我输入用户名并通过时会出现此错误。
因为代码中有以下 2 个未定义的行为:
scanf("%s",&UserName);
必须
scanf("%s",UserName);
和"最差":
scanf("%d",Password);
必须
scanf("%d", &Password);
否则scanf
尝试写入未初始化的密码值的未定义地址
可能是执行在scanf("%s",&UserName)
后继续,但在scanf("%d",Password)
产生典型的分段错误后没有机会
另请注意,密码必须是int
,或者格式必须类似于"%g"
但是使用浮点值作为密码是非常不可能的
除此之外,您还有其他未定义的行为
while (choice!=3){
因为选择永远不会初始化,但那一次的效果不像scanf("%d",Password);
那样"灾难性的"
另外你对什么期望:
char admin=admin;
必须删除该行,因为没有理由使用它
最后,在return 0;
之前缺少一个结束的"}"
我用一些缺少的东西更新了你的代码:
- 添加了 strcmp 所需的字符串.h 包含
- 删除了字符管理员 = 管理员
- 更新了密码扫描以使用正确的类型
始终尝试注意编译器,并在可能的情况下将所有警告激活为错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char UserName[100];
char admin[6] = "admin";
int Password;
int choice = 0;
while (choice != 3)
{
printf("Username : ");
scanf("%s", UserName);
printf("Password : ");
scanf("%d", &Password);
if (strcmp(UserName, admin) && (Password == 1234))
{
printf(" enter your choice : ");
}
return 0;
}
}