Search code examples
ccs50caesar-cipher

C: Reprompting to enter value into argv[] - without closing by error - Caesar Cipher


I am new to programming and I am undertaking CS50 harvard course on eDX. We had assignement for caesar cipher, I am quite satisfied with my code, even though it is not perfect. But I am not sure how to make program no to close by error when not providing any arguments.

According to the course assignement, it should be possible and the output should be "Usage: ./caesar key" - it is working if I use string instead of integer values or if there is multiple values inserted. But with empty values (./caesar) I am getting error in the terminal. Is there any way how to avoid this and just to close program like with entering string for instance? Have checked multiple topics already and being not able to find the was how to do it.

Thanks

PS: have already submited the assignement, but in my mind I am still returning to this topic and want to know if it is possible and how :D

#include <cs50.h>
#include <stdio.h>
#include <string.h>

int main(int argc, string argv[])
{
    int k = atoi(argv[1]);
    if (argc != 2 || argv[1] == NULL || k <= 0)
    {
        printf("Usage: ./caesar key\n");
        return(1);
    } 
    string p = get_string("Plaintext: ");
    printf("Ciphertext: ");

    //incrementing each letter
    for (int i = 0, n = strlen(p); i < n; i++)
    {
        //for capital letters
        if (p[i] >= 65 && p[i] <= 90)         
        {
            //refreshing alphabet char counting to 65
            if (p[i] + k > 90)
            {
                int m = ((p[i] + k) - 90);
                char c = 64 + m; 
                printf("%c", c);
            }
            else
            {
                printf("%c", p[i] + k);
            }
        }
        //for non-capital letters
        if (p[i] >= 97 && p[i] <= 122)         
        {
            //refreshing alphabet char counting to 97
            if (p[i] + k > 122)
            {
                int m = ((p[i] + k) - 122);
                char c = 96 + m; 
                printf("%c", c);
            }
            else
            {
                printf("%c", p[i] + k);
            }
        }
        //for non-letter characters
        if (p[i] < 65 || p[i] > 122)
        {
            printf("%c", p[i]);
        }
    }
    printf("\n");
}

Solution

  • You need to check the value of argc before you start accessing argv. So rather than setting k and then doing those checks, do most of the checks, then assign k and then check k is a legal value.

    int k;
    if (argc != 2 || argv[1] == NULL)
    {
        printf("Usage: ./caesar key\n");
        return(1);
    }
    k = atoi(argv[1]);
    if (k <= 0)
    {
        printf("Usage: ./caesar key\n");
        return(1);
    }