0

I think the most of my code is sound, but when I run Check50, it looks like perhaps my newline escape is not where it needs to be. I've moved it around some, but know I don't want it in my for loop. I'm wondering if to pass the check I have to set up my for loop as a function? Thanks in advance for any help!

Here are the errors I'm getting:

:) caesar.c exists
:) caesar.c compiles
:( encrypts "a" as "b" using 1 as key
\ expected output, but not "ciphertext:b\u0000\n"
:( encrypts "barfoo" as "yxocll" using 23 as key
\ expected output, but not "ciphertext:yxocll\u0000\n"
:( encrypts "BARFOO" as "EDUIRR" using 3 as key
\ expected output, but not "ciphertext:EDUIRR\u0000\n"
:( encrypts "BaRFoo" as "FeVJss" using 4 as key
\ expected output, but not "ciphertext:FeVJss\u0000\n"
:( encrypts "barfoo" as "onesbb" using 65 as key
\ expected output, but not "ciphertext:onesbb\u0000\n"
:( encrypts "world, say hello!" as "iadxp, emk tqxxa!" using 12 as key
\ expected output, but not "ciphertext:iadxp, emk tqxxa!\u0000\n"
:) handles lack of argv[1]

And here is my code:

int main(int argc, string argv[])
{
    //Tests that user input argv[1]
    if (argc != 2)
    {
        printf("Please add a second command-line argument!\n");
        return 1;
    }
    //Converts key from string to int
    int k = atoi(argv[1]);

    //Gets plaintext input from user
    printf("plaintext:");
    string p = GetString();

    //Begins to print ciphertext result
    printf("ciphertext:");

    for (int i = 0, n = strlen(p); i <= n; i++)
    {   
        char c = (p[i]);

        if (isalpha(c))
        {
            if (isupper(c))
            {
            c = c - 65;
            printf("%c", ((c + k) % 26) + 65);
            }
            else if (islower(c))
            {
            c = c - 97;
            printf("%c", ((c + k) % 26) + 97);
            }
        }
        else
        {
        printf("%c", c);
        }
    }
    printf("\n");
    return 0;
 }

1 Answer 1

1

Very subtle error here for (int i = 0, n = strlen(p); i <= n; i++). What is p[i] when i equals n? It is the null terminator of the string, '\0'. Which is a ascii 0. Which is \u0000 in unicode. The last valid index of p is one less than the strlen.

1
  • UPDATE: That took care of it! Passed now. Thanks! Oh, thank you so much! That was a later edit I experimented with to try to address a different issue I was getting and I forget to go back and look at it. I will revise it right now. That was extremely helpful. Thanks!
    – learner
    Commented Feb 13, 2017 at 0:49

You must log in to answer this question.

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