0

as the title says, I have most of the characters correct in the output compared to what it says in the instructions for pset2 Vigenere but a few of them are off, any help would be appreciated!

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

int main(int argc, string argv[])
{
if(argc != 2)
{
    printf("IDIOT!\n");
    return 1;
}    

string key = argv[1];

for (int n = 0, keylength = strlen(key); n < keylength; n++)
{
    if(!isalpha(key[n]))
    {
        printf("You must enter a keyword with only letters, no numbers.\n");
        return 1;
    }
}

string p = GetString();
int l = strlen(key);

for(int i = 0, j = 0, n = strlen(p); i < n; i++)
{
    if(isupper(p[i]))
    {
        char upper = (p[i] - 65) + (key[j%l] - 97) %26 + 65;
        printf("%c", upper);
        j++;
    }
    else if(islower(p[i]))
    {
        char lower = (p[i] - 97) + (key[j%l] - 97) %26 + 97;
        printf("%c", lower);
        j++;
    }
    else if(isspace(p[i]))
    {
        printf(" ");
    }
}
printf("\n");
return 0;
}

when I input this with the keyword "bacon"

Meet me at the park at eleven am

I get this:

Neg� zf av �uf pc�x bt gzrwep oz

Which is close except for the unknown unicode characters

(Note: edited for clarity of the problem) Suggestions?

0

Simple. Your code assumes that the key is all lower case. check50 tests against mixed case keys and text.

BTW, your code handles letters and spaces. What happens if there's punctuation or numbers in the plaintext. You should print any non-alpha characters, not just spaces.

[EDIT] And after looking deeper, there's a simple oversight. Look at the following:

 char lower = (p[i] - 97) + (key[j%l] - 97) %26 + 97;

The idea of the %26 is to wrap back around when the encoding goes past z. BUT, because of the placement (or lack of placement) of parentheses, the % 26 only applies to the key and not p[i]. Here's the fix:

char lower = (  (p[i] - 97) + (key[j%l] - 97)  ) %26 + 97;

This cleans up the encoding.

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

1
  • I have not run it against Check50 yet, this is just in testing so far. I was planning on adding checks for upper case characters in the key once I got the basic program to run correctly. I also have tests for non alpha characters but didn't put them in yet as well. This is just a test of the program using the suggested "Meet me at the park at eleven am" which gives me the result "Neg� zf av �uf pc�x bt gzrwep oz" – Kerry Oct 11 '15 at 21:36

You must log in to answer this question.

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