How to handle handles lack of argv[1] and handles too many arguments in caesar?

Viewed 18

I finished Caesar pset2 for CS50, but when I run it for a check-up, I get 2 errors. One for how handles lack of argv[1] and the other being too many arguments. I've been stuck on this for several hours and haven't made any progress. Any tips on how to move forward?

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

int main(int argc, string argv[])
{
    int strtoint;
    int onlydigits = 0;
    if (argc == 2) //Checks the program with one command-line argument
    {
        for (int i = 0, n = strlen(argv[1]); i < n; i++)
        {
            if (isdigit(argv[1][i]))
            {
                onlydigits += 1;
            }
        }
        if (onlydigits == strlen(argv[1])) //Checks if characters are digits
        {
            strtoint = atoi(argv[1]); //Converts string to int

            string plain = get_string("plaintext: "); //Prompt user for input
            printf("ciphertext: ");
                for (int j = 0, m = strlen(plain); j < m; j++) //Iterate over each character for plaintext
        {
            if (isalpha(plain[j]) && isupper(plain[j])) //Checks if characters are uppercase
            {
                printf("%c", (((plain[j] - 65) + strtoint) % 26) + 65);
            }
            else if (isalpha(plain[j]) && islower(plain[j])) //Checks if characters are lowercase
            {
                printf("%c", (((plain[j] - 97) + strtoint) % 26) + 97);
            }
            else
            {
                printf("%c", plain[j]); //Prints as is if neither of the above
            }

        }
        printf("\n"); //Prints a new line
        return 0;
    }
    else
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
}
}

output for code

0 Answers
Related