0

Problem with the shift value function ##

Hi, Could anyone please take a look at the code below and help me figure out where it goes wrong. I think the problem is with the shift_value. The code compiles, and runs. But the outcome with for example:

./vigenere a

plaintext: ji

ciphertext: cjui

thus adding letters, and not shifting them...

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

#define N_LETTERS 26
#define VALUE_OF_LOWERCASE_A 97
#define VALUE_OF_UPPERCASE_A 65

int main(int argc, string argv[])
 {
    string key = argv[1];
// re-ask if not two only
if (argc != 2)
{
    printf("Usage: ./vigenere keyword\n");
    return 1;
} 
// ensure only letters, string key = argv[1]
for (int i = 0, key_length = strlen(key); i < key_length; i++)
{
    if (!isalpha(key[i]))
    {
      printf("Usage: ./vigenere keyword\n");
      return 1; 
    }  
}
// get plain text 
string text = get_string("plaintext: ");
// skip spaces in plaintext
//int j = 0; 
printf("ciphertext: ");

//for each letter, encrypt by shifting variable steps
char key_val, cipher_char;
int shift_value;
for (int i = 0, text_length = strlen(text); i < text_length; i++)
{
    // loop through key 
    //j = j % strlen(argv[1]);

    // Get key_value
    key_val = key[i%text_length];
    //check case and convert from plain to cipher
    if islower(text[i])
    {
        shift_value = VALUE_OF_LOWERCASE_A - key_val;
        //cipher_char = text[i] + shift_value;
        cipher_char = (text[i] + shift_value) % N_LETTERS + VALUE_OF_LOWERCASE_A;
        printf("%c", cipher_char);
    }
    else if isupper(text[i])
    {
        shift_value = VALUE_OF_UPPERCASE_A - key_val;
        //cipher_char = text[i] + shift_value;
        cipher_char = (text[i] + shift_value) % N_LETTERS + VALUE_OF_UPPERCASE_A;
        printf("%c", cipher_char);
    }
    printf("%c", text[i]); 
}
printf("\n");
return 0;

}

Thank you!

1

When do you want this printf("%c", text[i]); to execute? When does it actually execute? Spoiler: once for every char in text. That explains the "doubling".

I will also warn that this key_val = key[i%text_length]; is going to cause heartbreak. The key is not "attached" to the text either by length or by index. Remember you don't "use" a k character when the text is not alpha. And in the example text_length is 2, but the key is only length of 1. Perhaps review the "panda" example in the short again.

1
  • Ok, that makes sense! Thank you, I'll try that. – thonje34 Mar 16 '19 at 7:20

You must log in to answer this question.

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