0

When i run my code, everything seems to be fine apart from the printing of the ciphertext, and the code doesnt seem to be getting passed the for loop of the string length of plain. Any ideas?

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

int main(int argc, string argv[])
{
    //check for a single command line argument 
    if (argc > 2 || argc < 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    else if (argc == 2)
    {
        //create an integer to store the key, and validate the key
        bool valid = true;
        int k = atoi(argv[1]);
        for (int i = 0; i < strlen(argv[1]); i++)
        {
            if ((isalpha(argv[1][i])))
            {
                valid = false;
                printf("Usage: ./caesar key\n");
                return 1;
            }
        }
        // if command line conditions are met, continue with the program
            if (valid == true)
            {
                // get a plaintext
                string plain = get_string("Plaintext: ");
                printf("Ciphertext: ");
                for (int i = 0; i < strlen(plain); i++)
                //print cipher text based on upper and lower case 
                {
                    if isupper(plain[i])
                    {
                        // add key k to text plain, adding and minusing a character on each side to round through 'Z'
                        printf("%c", (((plain[i] + k) - 'C') % 26) - 'C');
                    }

                    if islower(plain[i])
                    {
                        // add key k to text plain, adding and minusing a character on each side to round through 'z'
                        printf("%c", (((plain[i] + k) - 'c') % 26) - 'c');
                    }

                    // print any non alphabetic characters
                    else
                    {
                        printf("%c", plain[i]);
                    }
            }
            printf("\n");
            return 0;
        }
    }
}

0

This is the encoding formula:

         printf("%c", (((plain[i] + k) - 'C') % 26) - 'C');

Two things I don't understand. First, why subtract 'C' and not 'A'?

Second, why are you subtracting 'C' twice? The purpose of subtracting is to convert the letter from ASCII to a number from 0 to 25. Then, it needs to be added back to convert back to ASCII.

There may or may not be other issues.

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

1
  • Thanks for that. I used C simply for cipher text, no other reason really. Thanks for pointing out my typo. Seems to have fixed the problem. – anonymous May 7 '20 at 2:17

You must log in to answer this question.

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