0

This is my code:

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

int main(int argc, string argv[])
{

    int index =0;
    if (argc != 2)
    {
        printf("add one line argument\n");
        return 1;
    }

    string k = argv[1];
    string s;

    if (! isalpha(k[index]))
    {
        printf("only an alphabetic key\n");
        return 1;
    }

    s = get_string("plaintext:  ");
    printf("ciphertext:  ");

    int i, n;
    for (i = 0, n = strlen(s); i < n; i++)
    {
        if (islower(s[i]))
        {
            printf("%c", (s[i] - 97 + toupper(k[index])% 26 + 97));
            index = (index + 1)% n;
        }
        else if (isupper(s[i]))
        {
            printf("%c", (s[i] - 65 + (k[index]% 26 + 65)));
            index = (index + 1)% n;
        }
        else
        {
            printf("%c", s[i]);
        }
    }
    printf("\n");
    return 0;
}

It compiles, rejects non-alphebetic keywords, but encrypts incorrectly or improperly. It gives me the following encryption with an 'ABC' key and a 'hello' plaintext:

/workspace/ $ cd pset2
~/workspace/pset2/ $ cd vigenere
~/workspace/pset2/vigenere/ $ ./vigenere
add one line argument
~/workspace/pset2/vigenere/ $ ./vigenere 2
only an alphabetic key
~/workspace/pset2/vigenere/ $ ./vigenere ABC
plaintext:  hello
ciphertext:  us{l|
0

A few things.

First, you don't reject H4xx0r as a keyword.

Then, you apply +97 and +65 not as the last step of the formula, which it should be, directly after you %26 everything else. This ensures everything stays in alphabetic character range.

Third, you use k as if it were the number of characters to shift by. But it's an alphabetic character (given you fixed the initial check), and for example 'a' and 'A' both correspond to no shift, 'b' and 'B' stand for a shift of one letter, and so on.

0

Hmmmm.....

Along with what Blauelf pointed out, let's look at the critical error. (Sorry, Blauelf. )

printf("%c", (s[i] - 97 + toupper(k[index])% 26 + 97));

The formula subtracts 97 from s[i]. What about k[index]???

There's also the issue that the code is using the length of the plaintext to wrap around to the beginning of the key string.

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

0

You must log in to answer this question.

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