0

I've been struggling with PSet2's Vigenere cipher for a few days now, because of one error that I can't seem to fix. Every time I compile this program, the terminal gives me this error: /opt/sandbox50/bin/run.sh: line 31: 11290 Segmentation fault stdbuf --error=0 --output=0 "$@" Also, the cipher seems to be outputting unicode characters instead of actual letters, such as \u0013.

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


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

string k = argv[1];
int klen = strlen(k);


if (argc != 2)
{
    printf("Please enter one argument!\n");
    return 1;
}

for (int i = 0; i < klen; i++)
{
    if (isalpha(k[i]) == false)
    {
        printf("Please enter a valid string!");
        return 1;
    }
}

string p = GetString();
int plen = strlen(p);


for (int j = 0; j < klen; j++)
{
    k[j] = toupper(k[j]) - 65;

    for (int i = 0; i < plen; i++)
    {       

        if (isalpha(p[i]))
        {            
            p[i] = (p[i] + k[j]) % 26;
            printf("%c\n", p[i]);
        }
    } 
}
}
1

To clarify: the error /opt/sandbox50/bin/run.sh: line 31: 11290 .... is from check50, not from compile. It happens when check50 tests for "handles lack of argv[1]". That is because you do string k = argv[1]; before you know if there is an argv[1]. Technically, the segfault comes from the call to strlen(k).

The reason you are getting strange output is here: p[i] = (p[i] + k[j]) % 26;. You are using the ascii value of p[i] (97 for a) instead of the "alphabet index" of p[i] (0 for a). The result of your equation when p[i] = 'a' and k[j] = 'a' will be 19. p[i] needs to be in "alphabet index" for this math to work. The result then needs to be transformed to an ascii value for correct output. Don't forget to keep the correct case of p[i] when you make your corrections.

2
  • Thank you for your advice on the segmentation fault error, but I'm having trouble understanding why p[i] = (p[i] + k[j]) % 26; will not work. Say for example, the key is b. In the k[j] loop I convert that to uppercase (giving it a value of 66) and then subtract 65, making the key 1. I then add that key to each character in the plaintext (which shifts the letters by 1), and modulo 26 to wrap around. Shouldn't this work?
    – Alif Munim
    Nov 21 '15 at 3:01
  • The answer has been edited for clarity. It explains why your logic doesn't work. Nov 22 '15 at 18:11

You must log in to answer this question.

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