[英]C - Why it can't run correctly? I am new to C
The following code is running, but when I enter the username and the correct password it is always printing " The username doesn't exist. Try again with another username please. " Why? 下面的代码正在运行,但是当我输入用户名和正确的密码时,它始终显示“ 该用户名不存在。请使用另一个用户名再试一次。 ”为什么?
#include <stdio.h>
#include <string.h>
#define MAX_PASSWORD_LENGTH 10
#define MAX_USERNAME_LENGTH 10
#define MAX_USERS 15
int main(void) {
char usernames[MAX_USERS][MAX_USERNAME_LENGTH + 1] = { "nnikolaou", "stakis",
"sanitsaki" };
char passwords[MAX_USERS][MAX_PASSWORD_LENGTH + 1] = { "n32", "s4343",
"s5343" };
char user_access_rights[MAX_USERS] = { 'r', 'a', 's' };
int i;
char username_entered[MAX_USERNAME_LENGTH + 1];
char password_entered[MAX_PASSWORD_LENGTH + 1];
float ret1;
int abc;
int username_position;
abc = 0;
printf("Enter username please, with a maximum length of %ld characters:",
MAX_USERNAME_LENGTH);
for (i = 0; i < MAX_USERNAME_LENGTH; i++) {
username_entered[i] = getchar();
if (username_entered[i] == '\n') {
break;
}
}
printf("Enter password please, with a maximum length of %ld characters:",
MAX_PASSWORD_LENGTH);
for (i = 0; i < MAX_PASSWORD_LENGTH; i++) {
password_entered[i] = getch();
if (password_entered[i] == '\r') {
break;
}
putchar('*');
}
for (i = 0; i < MAX_USERS; i++) {
ret1 = strcmp(username_entered, usernames[i]);
if (ret1 == 0) {
username_position = i;
abc = 1;
printf("\n");
printf("The username has been found.");
} else {
if (i == MAX_USERS + 1) {
abc = 0;
}
}
}
if (abc == 0) {
printf("\n");
printf(
"The username doesn't exist. Try again with another username please.");
printf("\n");
return 1;
}
return 0;
}
I believe that it is problem of strcmp . 我相信这是strcmp的问题。 It should be written in this way, using strcmp.
应该使用strcmp以这种方式编写。
I see couple of problems. 我看到几个问题。
'\\n'
in the name when accepting user input. '\\n'
。 Tweak your code a little bit to fix those. 稍微调整一下代码即可解决这些问题。
for(i=0; i<MAX_USERNAME_LENGTH; /* i++ Increment i only in one branch */){
int c = getchar();
if ( c == '\r' )
{
// Ignore it.
// Don't increment i for this.
}
else if ( c == '\n')
{
break;
}
else
{
// Store the character and increment i.
username_entered[i] = c;
i++;
}
}
username_entered[i] = '\0';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.