这段代码应该输入用户名和密码。。用户名是Admin,密码是2016。如果用户正确输入,它将打印登录过程已成功完成,否则它将要求用户再次输入。。我编写了代码,但它不起作用,我不知道为什么。。在这里:
#include <stdio.h>
int main(){
char* *username[5]; int password,choice; char Admin,i;
printf("Welcome to the Students' Registration Systemn");
printf("Dear Registry employee: Kindly insert your username:n");
for (i=0;i<5;i++){
scanf("%c", &username[i]);
}
printf("Insert your password:n");
scanf("%d", &password);
if ((*username[5]=="Admin")&&(password==2016))
printf("The login process is successfully done");
else
while ((*username[5]!="Admin")||(password!=2016))
{
printf("The login process failedn");
printf("Dear Registry employee: Kindly insert the correct username and passwordn");
for (i=0;i<5;i++){
scanf("%c", &username[i]);
}
scanf("%d", &password);
}
printf("Please choose the number of your next step:n");
printf("[1]Add new studentn");
printf("[2]Add new coursen");
printf("[3]Assignremove courses for the studentn");
printf("[4]Search and view students' details:n");
printf("[5]Request reports:n");
printf("[6]Update student/course record:n");
printf("[7]Delete student/course record:n");
return 0;
}
您的程序存在多个问题,其中包括:
- 将
username
转换为指向字符指针的指针数组 username
的长度不足以容纳默认密码admin
- 使用循环读取用户名
- 使用
==
和!=
运算符比较字符串
更好的方法如下。
#include <stdio.h>
#include <string.h>
int main()
{
//Admin has 5 characters, and string requires one null terminator. So minimum length should be 6
char username[10];
int password,choice;
char Admin,i;
printf("Welcome to the Students' Registration Systemn");
do
{
printf("Dear Registry employee: Kindly insert your username:n");
//Use %s to read a string completely(till white space character)
scanf("%s", username);
printf("Insert your password:n");
scanf("%d", &password);
//You can't compare string using == or !=
}while (strcmp(username, "admin") != 0 && password != 2016 );
printf("The login process is successfully done");
printf("Please choose the number of your next step:n");
printf("[1]Add new studentn");
printf("[2]Add new coursen");
printf("[3]Assignremove courses for the studentn");
printf("[4]Search and view students' details:n");
printf("[5]Request reports:n");
printf("[6]Update student/course record:n");
printf("[7]Delete student/course record:n");
return 0;
}
如何在C中读取/解析输入?常见问题。。从"请勿将*scanf()
用于可能格式错误的输入"一节开始,然后继续阅读。
我不给家庭作业问题现成的答案,但对你的特定问题有一些提示:
char* *username[5]
这是一个由5个指针组成的数组,这些指针指向指向char
的指针。不是你想要的,真的。您需要一个字符数组,也称为"字符串"。
for (i=0;i<5;i++){
scanf("%c", &username[i]);
}
此(%c)每次读取一个字符。同样,您需要一个字符串。使用scanf( "%s", ... )
,您可以这样做,但您确实不应该这样做。您需要fgets()
。
if ((*username[5]=="Admin")&&(password==2016))
username[5]
?你一次读一个字之后?你看到问题了吗?
您可能对一个名为strncmp
的函数感兴趣。