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

I'm trying to come up with a code where to check if the password contains only letters. Why does this code only work with the " == 0" sign. My friend told me to put this and my code works. What does the " == 0" do?

delta
  • 3,778
  • 15
  • 22
sangmin park
  • 547
  • 3
  • 7
  • 16
  • If you don't want `==0`, try `if(!isalpha(userPassword))` – cs95 Aug 14 '17 at 01:29
  • You are only reading and testing one char, not a string. – stark Aug 14 '17 at 01:47
  • `isalpha` returns '0' (false) if test fails, otherwise it returns non-zero(true) if the test passes. So, use '!' as suggested above. – Serge Aug 14 '17 at 02:22
  • 1
    The line `scanf("%c", &userPassword);` is wrong on multiple accounts. You read a single character into an array; you pass a pointer to an array where a pointer to a character is expected; you don't don't check the return value from `scanf()`; you're liable to problems with leftover newlines etc after this input. It isn't clear whether you want 1-character passwords (hint — they're not secure) but then why bother with an array of 20 characters. (Only 20 characters including null; darn it — there goes my favourite password scheme!) – Jonathan Leffler Aug 14 '17 at 03:04
  • Oh, and `isalpha()` expects a single character; you're passing a pointer to it. The compiler should be complaining. Don't post non-compiling code unless you state that you can't get it to compile and show what the error messages are. And make sure that what the code is an MCVE ([MCVE]). – Jonathan Leffler Aug 14 '17 at 03:06
  • The code *doesn't* work with that. – user253751 Aug 14 '17 at 05:48

1 Answers1

2

The signature of isalpha is int isalpha ( int c ).

  • Parameters c character to classify

  • Return value Non-zero value if the character is an alphabetic character, zero otherwise.

So, if c is not alpha, it returns non-zero, otherwise 0.

About the program:

  1. scanf needs char *, not &userPassword, which is char **. scanf("%s", userPassword) is OK.
  2. pass char to isalpha instead of char *.

If you want to check if a string is all alpha, you can simply iterate the string and check each single character. Like:

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
delta
  • 3,778
  • 15
  • 22