mardi 23 mai 2017

How To Check For Non-Alphabetical Characters in String in C

The below code (which compiles fine) checks for non-alphabetical characters in a command-line input, however I feel like there's got to be a better way to write this. For example, you can see that there is no code that executes in the core if statement that checks each character in the string. Is there a way to check if one of the characters is not an alphabetical character and throw the error, rather than have the error in the else function?

int main(int argc, string argv[]){

    // terminate program if more than one key
    if(argc != 2){

        printf("error");
        return 1;

    // check to ensure key characters are alphabetical
    } else {
        for(int h = 0; h < strlen(argv[1]); h++){
            if(isalpha(argv[1][h])){

            } else {
                printf("error");
                return 1;
            }
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire