1

I am kind of stuck with my Vigenere Code so far... and i really feel like don´t know how to work it out from here! Any kind of advice is much appreciated, or i might be stuck here forever :(

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

int main(int argc, string argv[])
{
  if (argc != 2)
{
  printf("Please enter a key for the vigenere Cipher as commandline
  argument!\n");
  return 1;
}

int plainLen;
int keyValue;
string key = argv[1];
string plain;

for (int i = 0, n = strlen(key); i < n; i++)
{
  if (isalpha(key[i]))
  {
    if (islower(key[i]))
    {
        toupper(key[i]);
        keyValue = key[i] - 65;
    }
    else
    {
        keyValue = key[i] - 65;
    }

  }

}

printf("plaintext: ");
plain = GetString();
plainLen = strlen(plain);

printf("ciphertext: ");
for (int i = 0; i < plainLen; i++)
{
    if (isupper(plain[i]))
    {
        printf("%c", (((plain[i] - 65) + key[i]) % 26) + 65);
    }
    else
    {
        printf("%c", (((plain[i] - 97) + key[i]) % 26) + 97);
    }

}
printf("\n");
}
1

A few problems.

You should abort if the keyword contains any non-alphabetic character.

toupper does not change a variable, it returns the uppercased version of whatever you put in. You'll need an explicit assignment if you want it to replace a value.

You assign to keyValue multiple times, leaving only the last value. You never use the value then. Maybe you meant something like key[i] = toupper(key[i]) - 65; (if key[i] is uppercase, toupper would not change anything).

In the encryption part, don't forget to pass non-letters in plaintext unchanged. In case of such characters, don't advance in the key, meaning you need a separate key index, incremented only on encrypting a letter.

0

I think part of your problem is that you aren't accounting for the code beforehand. If you establish that the given key and to-be-encoded-text are capital letters beforehand, then you never need to check them during the encoding part.

Also, because the characters can be considered integers by the compiler (is this right? I'm new too), you can refer to them as numbers instead of worrying about their actual value. Then the problem becomes a lot easier and you can focus on the arrays.

You must log in to answer this question.

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