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

int main (int argc, string argv[])
{
    //validating command line input

    if (argc != 2 )
    {
        printf("usage: ./vignere k\n");
        return 1;
    }


    //storing argument into variable

    string key = argv[1];
    int n = 0;

    //iterating over key, making everything lowercase and checking key

    for (int j = 0; j < strlen(key); j++)
    {
        if (!isalpha( key[j]) )
        {
            printf("wrong key\n");
        }

        else if (isupper(key[j]))
        {
            key[j] = key[j] - 65;
        }
        else if (islower(key[j]))
        {
            key[j] = key[j] - 97;
        }
    }

    //obtaining user input

    printf("Input plaintext:\n");
    string text = get_string();

    //iterating text


    for (int i = 0; i < strlen(text); i++)
        {

       //branching upper/lower

            if ( isalpha(text[i]) )
            {
                if (isupper(text[i]))
                {
                    text[1] = ( ( (text[i] - 65) + (key[n % strlen(key)]) ) % 26 + 65);
                    n++;
                    printf("%c", text[i]);
                }
            }
        }
2

Suppose the first letter of your key is 'a'. After your for loop is done, the value stored in key[0] is no longer 97 ('a'), but 0.

When you then, later, do strlen(key), the value returned is 0, because you no longer have a valid string, the first character is 0, so strlen sees a null terminator (a null terminator is always 0).

key[n % strlen(key)]

This expression will give that error because %0 requires dividing by 0.

You must log in to answer this question.

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