0

This is driving me mad. I think I have implemented Caesar correctly, but Vigenere does not seem to work. I've tried everything. Please, let me know what happens. PD Sometimes, the terminal, halfway through ciphering, prints 'Floating point exception (core dumped)'. I don't know why this happens.

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

  int main (int argc, string argv[])
  {
  string keyword = argv[1];
  int key;
  char ciphered;
  int h;
  int j;
  int plain;

 if (argc < 2)
  return 1;

 for (int o=0; o<strlen(keyword); o++)
 {
    if (!isalpha(keyword[o]))
     return 1;
 }

 string plaintext=GetString();

 h=strlen(keyword);

 for(int i=0; i<strlen(plaintext); i++)
 {
     j = ((strlen(keyword))%h);
     key=0;

     if (isupper(keyword[j]))
        key=(keyword[j]-65);

     if (islower(keyword[j]))
        key=(keyword[j]-97);

     plain=plaintext[i];

     ciphered=((plain+key)%26);

     if (isupper(plaintext[i]))
       ciphered+=65;

     if (islower(plaintext[i]))
       ciphered+=97;

     printf("%c\n", ciphered);

     ciphered=0;

     if (isalpha(plaintext[i+1]))
        h--;
 }
return 0;
}
1

The floating-point exception typically happens because of a division by 0. You get that because of your risky usage of the remainder operator. I'll let you play with this a little more to figure out exactly which line causes that.

Here are a couple more hints:

  • you should move to the next key in the keyword if and only if the current character in the plaintext is alphabetical.
  • make sure you move to the next key in the keyword correctly.
  • when encrypting, what if plain + key is out of bounds?

    For example, if plaintext[i] is 'z' which is equal to 122. And the current key is 'd' which is equal to 101. What you're basically doing is

      (122 + (101 - 97) % 26) + 97 
    = (126 % 26) + 97
    = 22 + 97 = 119 = 'w'
    

    is that correct? If not, how do you propose fixing it?

  • you have many unnecessary variables

  • you don't need to repeat the conditions. There's a more elegant way.

You must log in to answer this question.

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