0

My program will compile and run, but it prints out exactly what I enter in. I've run it through the debugger and it looks like it can't identify the different cases, so rather than split at the isupper() or islower() statements, it defaults to line 53 at

// if non-alpha

and prints as-is.

Am I not understanding what functions take what data types and when to convert and that's why isupper() and islower() don't see the ASCII cases?

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

int main(int argc, string argv[])
{
    // sanity check, error message
    if (argc != 2)
    {
        printf("Please enter exactly 2 command-line arguments\n");
        return 1;
    }

    // convert key to int
    int k = atoi(argv[1]);

    // get plaintext from user
    printf("plaintext: ");
    string p = get_string();

    printf("ciphertext: ");

    // iterate over p, preserve case
    for (int i = 0, n = strlen(p); i < n; i++)
    {
        if ('p[i]' == isalpha(p[i]))
        {
            // if upper case
            if (isupper(p[i]))
            {
                // ascii to numerical
                int ascii_up = (p[i] - 65);
                int index_up = (ascii_up + k) % 26;
                // numerical to ascii
                int ciph_up = index_up + 65;
                printf("%c", (char) ciph_up);
            }

            // if lower case
            else if (islower(p[i]))
            {
                // ascii to numerical
                int ascii_lo = (p[i] - 97);
                int index_lo = (ascii_lo + k) % 26;
                // numerical to ascii
                int ciph_lo = index_lo + 97;
                printf("%c", (char) ciph_lo);
            }
        }

        // if non-alpha
        printf("%c", p[i]);
    }

    printf("\n");

    return 0;
}
1

if ('p[i]' == isalpha(p[i]))

that says if 'p[i]' equals the value returned by isalpha(p[i]). That will never be true.

You want to say if (isalpha(p[i])) // if p[i] is alphabetic

Saying that though, you can just eliminate that entirely, since you next check if it's lowercase or uppercase. It can't be one of those if it isn't alphabetic, so no need to do that check first.

1
  • That did it! Thank you so much!
    – pdhannum
    Sep 8 '17 at 21:01

You must log in to answer this question.

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