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

int main(int argc, char *argv[])

{
    //create key
    string key = argv[1];


    //check if number of argument is not 2
    if (argc != 2)
    {
        printf("Usage: %s key\n", argv[0]);
        return 1;
    }



    //convert string to int

    int k = atoi(key);

    //prompt user for plaintext
    string p = get_string("plaintext: ");
    printf("ciphertext:");

    int n = strlen(p);

    //shift letters only
    //preserve case and iterate over each character
    //ASCII value then encipher back to ASCII
    for (int i = 0; i < n; i++)
    {
        if (isalpha(p[i]))
        {

          if (isupper(p[i]))
          {
          printf("%c", (((p[i] + k) - 65) % 26) + 65);
          }

          if (islower(p[i]))
          {
          printf("%c", (((p[i] + k) - 97) % 26) + 97);
          }
        }
        else //print character as is
        {
        printf("%c", p[i]);
        }



    }
    //print newline
    printf("\n");

    //program exit
    return 0;

}

This is almost done but not quite. I keep getting ":( handles non-numeric key; timed out while waiting for program to exit. I was thinking isdigit but I'm not sure that would work with atoi. Help please.

1 Answer 1

0

There are two ways to handle the non-numeric key. The first is using the isdigit function from ctype.h library. the isdigit function can be used to checked each character in the string. The second one is a very simple method.

# include<string.h>
...
for (int i = 0; i < strlen(argv[1]); i++){
    if ((argv[1][i] < '0')||(argv[1][i] > '9')){
        printf("Usage: ./caesar key\n");
        return 1;
    }
}
...

The for loop check if all the keys are numeric. If it finds a non-numeric key then it will end the program and exit.

Hope this helps. If it does, then please check the tickmark.

You must log in to answer this question.

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