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

int main() {
    char userPassword[20];

    printf("Type in your password: \n");
    scanf("%c", &userPassword);

    if (isalpha(userPassword) == 0) {
        printf("Nice");
    } else {
        printf("Nope");
    }

    return 0;
}

我试图想出一个代码来检查密码是否只包含字母。为什么此代码仅适用于“== 0”符号。我的朋友告诉我把这个和我的代码工作。“== 0”有什么作用?

4

1 回答 1

2

的签名isalphaint isalpha ( int c )

  • 参数 c 字符进行分类

  • 返回值 如果字符是字母字符,则为非零值,否则为零。

因此,如果c不是 alpha,则返回非零,否则返回 0。

关于节目:

  1. scanf需要char *,不是&userPassword,这是char **scanf("%s", userPassword)没关系。
  2. 传递charisalpha而不是char *.

如果你想检查一个字符串是否都是字母,你可以简单地迭代字符串并检查每个字符。喜欢:

bool is_all_alpha(char *s) {
    for (; *s!='\0'; ++s) {
        if (!isalpha(*s)) return false;
    }
    return true;
}

  1. http://en.cppreference.com/w/cpp/string/byte/isalpha
于 2017-08-14T03:25:57.227 回答