Search code examples
ccommand-line-argumentscs50caesar-cipher

CS50 Caesar cypher disrupts after checking command-line argument


I've been writing a code on Caesar's cypher (coding letters by shifting them by a number entered). It was working correctly until I introduced a condition ensuring the key entered is a digit and is somehow disrupts the code working.

I don't understand how this condition correlates with the code afterwards and what's wrong.

Could please someone help?

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

int main(int argc, string argv[])

{
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    for (int j = 0; j < strlen(argv[1]); j++)
    {
        if (!(isdigit(argv[1][j])))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }

    }


    int k = atoi(argv[1]);
    if (argc == 2 && k > 0)

    {
        string s = get_string("plaintext: ");

        int m = k % 26;

        //introducing an array type char of string length size
        char cypher[strlen(s)];


        for (int i = 0; i < strlen(s);  i++)
        {
            //checking if it's a letter, if yes then next if
            if (isalpha(s[i]))
            {
                //checking if it's uppercase
                if (isupper(s[i]))
                {
                    cypher[i] = (s[i] + m);
                    //make a round if it's beyond Z
                    if (cypher[i] > 'Z')
                    {
                        cypher[i] = cypher[i] - 26;
                    }

                }
                // checking if it's lowercase
                else if (islower(s[i]))
                {
                    //if it falls beyond ascii table
                    if ((s[i] + m) > 126)
                    {
                        cypher[i] = (s[i] - 26 + m );
                    }
                    else
                    {
                        cypher[i] = (s[i] + m);
                    }
                    //make a round if it's beyond z
                    if (cypher[i] > 'z')
                    {
                        cypher[i] = cypher[i] - 26;
                    }
                }

            }
            // if it's not a letter - keep the initial character, write it in the cypher
            else
            {
                cypher[i] = s[i];
            }
        }

        printf("ciphertext: %s\n", cypher);
        return 0;

    }



}

Solution

  • strlen in C doesn't take into account the null character The length of the array should be [strlen(s)+1] and the \0 character should be added