0

I am tearing my hair out on this exercise. I cannot get it to pass a non-numeric key. I've played around with the code for 2 weeks now. I can either get it to handle a numeric key or handle a lack of key, but not both. I've played around with isdigit and isalpha, and do while and if else statements. I feel like im missing something really obvious but for the life of me I cant get it. I didnt want to print my entire code but I cant figure out where my error is to show you so I will have to. Thank you for any advice you can give me.

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

int main(int argc, string argv[])

{
    string Key = argv[1];  //name string
    if (argc != 2)  //if argc = 1 + 1??
    {
        printf("Usage: ./caesar Key \n");
        return 1;
    }


    int k = atoi(Key) % 26; // convert string to int with stdlib and atoi
    
    
    if (k <= 0)  //if  int has 0 value
    {
        printf("Usage: ./caesar Key \n");
        return 1;
    }
 

    string Input = get_string("plaintext: "); //get unciphered text
    printf("ciphertext: \n");  //return ciphertext

    for (int i = 0, n = strlen(Input); i < n; i++)  //loop to encrypt letters individually
    {
        int x = 0;
        if (isupper(Input[i]))
        {
            x = (((int)Input[i] - 65 + k) % 26) + 65;
            printf("%c", (char)x);
        }

        else if (islower(Input[i]))
        {
            x = (((int)Input[i] - 97 +  k) % 26) + 97;
            printf("%c", (char)x);
        }

        else
        {
            printf("%c", Input[i]);
        }
    }
    
    printf("\n");
    return 0;

}
1

First of all, the code MUST check for lack of a key, i.e., a valid number of parameters by checking the value of argc FIRST!!! Right now, the code is trying to use argv[1] before checking the value of argc, meaning that it's trying to use an array element that might not even exist! That should solve some of your issues.

Next, there's no code at all to verify that each character in argv[1] is numeric. Think carefully about what I just said.

That should resolve the rest of your validation issues.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thanks Cliff B. I had previously tried a loop for the key, but I wasn't using it correctly so I mistakenly took it away. I ran debug50 (another tool I had completely ignored) to take myself through the program and realised my syntax meant that my program was just jumping over the most important part of my code. Rookie mistakes. I think I will go back and attempt the comfortable exercise to make sure the principles are sinking in. Thanks for the help, i notice you comment a lot on here and slack to help newbies like me so thanks again. – Chris Causey Jul 4 '20 at 12:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .