0

I think I am getting close on Pset2 substitution. But every time I run this code it outputs my ciphertext as void. There's obviously something wrong with my loops converting plaintext to ciphertext but I'm not sure what. Can anyone else see where I am going wrong here?

I should add the caveat that I know I need to add code about upper case and lower case text here, but wanted to work through the core issue of converting my plaintext to ciphertext first.

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

int main(int argc, string argv[1])
{
    // Declare variables
    string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string ciphertext = NULL;
    string key = argv[1];

    // Prompt user again for key if needed
    if (argc != 2)
    {
        printf("Usage: ./substitution key \n");
        return 1;
    }

    // Check for valid key
    int counter = 0;
    while (key[counter] != '\0')
    {
        if (isalpha(key[counter]))
        {
            counter++;
        }
        else
        {
            printf("Key must contain 26 characters. \n");
            return 1;
        }
    }
    if (counter < 26 || counter > 26)
    {
        printf("Key must contain 26 characters. \n");
        return 1;
    }

    // Get plaintext from user
    string plaintext = get_string("plantext: ");

    // TODO adjust to handle upper and lowercase letters
    int x = 0;
    while (plaintext[x] != '\0')
    {
        printf("%c\n", plaintext[x]);
        for (int i = 0; i < 26; i++)
        {
            if (plaintext[x] == alphabet[i])
            {
                ciphertext[x] = key[i];
                printf("%c\n", ciphertext[x]);
            }
        }
        x++;
    }

    // Print ciphertext
    printf("%s\n", ciphertext);
    return 0;
}

1 Answer 1

0

The biggest problem is early in the code:

string ciphertext = NULL;

This declares the var ciphertext, but doesn't allocate any space for it!

The code needs to allocate space for the entire string. Since you don't know how long the string is (plus 1 for the end of string marker), it needs to be done after the code gets the plainstring from the user. Hint: strlen() is your friend.

You might find it useful to remove some of the line feeds, ie, \n from some of the printf statements.

Also, be sure that the plaintext string is UPPERCASE until you add the mixed case code or it will fail.

Finally, how does the code handle non-alpha characters? Or have you not done that yet? ;-)

You must log in to answer this question.

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