0

Please help me! Something wrong with wrapping around the keyword in my code. Here is the code:

// only one command-line argument
if (argc != 2)
{
    printf("write a valid key!!!\n");
    return 1;
}

// command-line argument contains only alphabetical chars
for (int c = 0, l = strlen(argv[1]); c < l; c++)
{
    if (!isalpha(argv[1][c]))
    {
        printf("write a valid key!!!\n");
        return 1;
    }
}

// gets user's text
string text = GetString();

for (int i = 0, c = 0, n = strlen(text); i < n; i++)
{
    // for letters
    if (isalpha(text[i]))
    {
        // for uppercase
        if (isupper(text[i]))
        {
            if (isupper(argv[1][c]))
            {
                printf("%c", ((((text[i] - 65) + (argv[1][c % strlen(argv[1])] - 65)) % 26) + 65));
            }
            else
            {
                printf("%c", ((((text[i] - 65) + (argv[1][c % strlen(argv[1])] - 97)) % 26) + 65));
            }
        }
        // for lowercace
        else
        {
            if (isupper(argv[1][c]))
            {
                printf("%c", ((((text[i] - 97) + (argv[1][c % strlen(argv[1])] - 65)) % 26) + 97));
            }
            else
            {
                printf("%c", ((((text[i] - 97) + (argv[1][c % strlen(argv[1])] - 97)) % 26) + 97));
            }
        }
        c++;
    }

    // for symbols and numbers
    else
    {
        printf("%c", text[i]);
    }
}

printf("\n");
return 0;

Here is the result of check50: enter image description here

Thanks in advance!

3

Look at your tests on the key. Here's one of them:

if (isupper(argv[1][c]))

When you encode a letter, you apply the modulo operation correctly to the key to get the right character, but when you are doing this test, you are checking for isupper() beyond the end of the key.

Instead of doing so many modulo operations in the code to get the right index from c, wouldn't it be safer, easier, and more efficient to do this: at the bottom of the code where you increment c, why not apply the modulo operation there and reset it to 0 when it reaches the end of the key? If you increment c, and then modulo, it will not change anything when c < key length, and will reset to 0 when c = key length.

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

1
  • Thank u very much! You are my code saver! :) – Yana Mikhnich Sep 21 '15 at 15:48

You must log in to answer this question.

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