2017-08-14 59 views
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」是做什麼的?檢查`isalpha`的返回值

+0

如果你不想'== 0',試着去'如果(因而isalpha(userPassword的)!)' –

+0

你只是閱讀和測試一個字符,而不是一個字符串。 – stark

+0

如果測試失敗,則'isalpha'返回'0'(假),否則如果測試通過則返回非零(真)。所以,使用'!'如上所述。 – Serge

回答

2

isalpha的簽名是int isalpha (int c)

  • 參數 c字符來

  • 返回值 非零值分類如果字符是字母字符,否則爲0。

所以,如果c不是字母,則返回非零值,否則爲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
+2

'&userPassword'是'char(*)[20]',而不是'char **' –