mardi 5 octobre 2021

Why does it say 'Segmentation Fault'?

Why does it say 'Segmentation Fault' when I run the following code?

Also, I know it's related to isdigit(argv[1]) > 0 in line 13, because when I exclude it then everything works fine.

I need it to verify that the argument given is a number.

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

//main method
int main(int argc, char *argv[]) {

    //
    if ((argc == 2) && (isdigit(argv[1]) > 0)) {
        int key = atoi(argv[1]);
        string plainText = get_string("plaintext: ");

        printf("ciphertext: ");

        for (int i = 0; i < strlen(plainText); i++) {
            if (isupper(plainText[i])){
                char cipherText = (plainText[i] - 65 + key) % 26 + 65;
                printf("%c", cipherText);
            } else if (isalpha(plainText[i])) {
                char cipherText = (plainText[i] - 97 + key) % 26 + 97;
                printf("%c", cipherText);
            } else {
                printf("%c", plainText[i]);
            }
        }
        printf("\n");
    }
    else {
        printf("Proper usage: ./caesar (cipher key)\n");
        return 1;
    }

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire