C - 为什么它无法正常运行?我是C的新手

时间:2016-06-28 18:38:22

标签: c

以下代码正在运行,但是当我输入用户名和正确的密码时,它始终打印“用户名不存在。请再次使用其他用户名。”为什么?

#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;
}

我认为这是 strcmp 的问题。它应该用这种方式编写,使用strcmp。

1 个答案:

答案 0 :(得分:4)

我看到了几个问题。

  1. 接受用户输入时,您在名称中包含'\n'
  2. 使用空字符终止名称。
  3. 稍微调整一下你的代码来修复它们。

    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';