C中字符数组中的字符串终止符

-1 c arrays terminator

我正在尝试根据一组规则制定一个程序来决定密码的有效性.

这是我有的:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>

int main()
{
  int uppercase = 0;
  int length = 0;
  int numbers = 0;
  int others = 0;
  char password[13];
  char yesOrNo;
  printf("Your password must be 8-12 characters long.\n"
         "It must contain at least one symbol, uppercase letter, and number.\n\n");
 COMEBACK:
  printf("Please enter your password:");
  scanf(" %s", &password);
  while (password != 'NULL') { // Tried 0 here, tried '\0', but to no avail.
    if (isalpha(password)) {
      length += 1;
      if (isupper(password)) {
        uppercase += 1;
      }
    }
    else if (isdigit(password)) {
      numbers += 1;
      length += 1;
    }
    else {
      length += 1;
    }
    // This is just a test, to see if it was working.
    printf("%d - %d - %d - %d --- %s",
           uppercase, length, numbers, others, password);
  }
  if ((uppercase > 0) && (numbers > 0)
      && (length >= 8) && (length <= 12) && (others > 0)) {
    printf("Good job, you've done your password correctly.");
  } else {
    printf("%d - %d - %d - %d --- %s \t Incorrect..",
           uppercase, length, numbers, others, password); // Same thing here.
    scanf("%s", &yesOrNo);
    switch (yesOrNo) {
    case 'y':
      goto COMEBACK;
      break;
    case 'n':
      printf("Sorry you're dumb man..");
      break;
    default:
      printf("Please enter a valid password.");
    }
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,while循环永远不会结束,因为它似乎找不到我的密码数组的终结符.我输入'\ 0'和'0'.但我仍然无法弄明白.任何帮助表示赞赏.谢谢.

Jon*_*ler 5

这段代码:

while (password != 'NULL') { 
Run Code Online (Sandbox Code Playgroud)

应该是丰富的编译器警告.多字符文字是不可移植的,不应与指针进行比较.

您可能需要:

char *ptr = password;
while (*ptr != '\0') {
    ...
    ptr++;
}
Run Code Online (Sandbox Code Playgroud)

或(C99或更高版本):

for (char *ptr = password; *ptr != '\0'; ptr++)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

并且用于*ptr识别字符(或者,通常,(unsigned char)*ptr因为普通字符经常char被签名并且isalpha()等等需要正值或EOF作为输入值).如果你没有C99,你可以char *ptr;在循环外声明并删除char *循环控件内部.

你有:

if (isalpha(password)) {
Run Code Online (Sandbox Code Playgroud)

因为password是一个数组,所以你将一个固定的指针传递给一个需要非pointer(int)值的函数.我可能会在循环中添加:

{
    unsigned char uc = *ptr;
    if (isalpha(uc))
        ...
Run Code Online (Sandbox Code Playgroud)

请注意,您可能只需要一个length++;用于所有情况.

另请注意,任何密码都不会满足'至少一个符号'标准,因为您永远不会增加others.

并且goto可以用while()可以检测EOF 的循环代替:

while (scanf("%12s", password) == 1)
{
    length = others = uppercase = numbers = 0;  // Ignore previous attempts
    for (char *ptr = password; *ptr != '\0'; ptr++)
    {
        unsigned char uc = *ptr;
        length++;
        ...character testing code...
    }
    ...validity checking code...
}
Run Code Online (Sandbox Code Playgroud)

在学习C时,假设编译器警告是严重错误.它比你在这个阶段更了解C.