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


int main(int argc, string argv[])
{
    int k, j, i = 0, ch, pos;
    bool alpha = true;
    string in = GetString();
    int num = strlen(in);

    for (int z = 0; z < strlen(argv[1]); z++)
    {
        if ( !(isalpha(argv[1][z]) )
        {
            alpha = false;
        }
    }

    if (argc != 2 || !alpha)
    {
        printf("Dude we only accept alphabets...");
        return 1;
    } 

    string key = argv[1];
    int keylength = strlen(key);

    for (i = 0, j = 0; i < num; i++, j++)
    {
        if (isupper(key[i]))
        {
            k = key [j % keylength] - 'A';
        }

        if (islower(key[i]))
        {
            k = key[j % keylength] - 'a';
        }

            if (isupper(in[i]))
            {
                pos = in[i] - 'A';
                ch = ((pos + k) % 26) + 'A';
                printf("%c", ch);
            }

            if (islower(in[i])){
                pos=in[i] - 'a';
                ch = ((pos + k) % 26) + 'a';
                printf("%c", ch);
            }

            if (isspace(in[i]))
            {
                printf(" ");
            }

            if (ispunct(in[i]))
            {
                printf("%c", in[i]);
            }
    }

    printf("\n");
}

Here is the result of check50:

Output condition checks:
:) vigenere.c exists

:) vigenere.c compiles

:) encrypts "a" as "a" using "a" as keyword

:( encrypts "world, say hello!" as "xoqmd, rby gflkp!" using "baz" as keyword

\ expected output, but not "xoqkj, yfd gfllp!\n"

:( encrypts "BaRFoo" as "CaQGon" using "BaZ" as keyword

\ expected output, but not "CaQEun\n"

:( encrypts "BARFOO" as "CAQGON" using "BAZ" as keyword

\ expected output, but not "CAQEON\n"

:( handles lack of argv[1]

\ expected output, not a prompt for input

:( handles argc > 2

\ expected output, not a prompt for input

:( rejects "Hax0r2" as keyword

\ expected output, not a prompt for input

What is wrong with my code? I have scrutinized the logic and the error seems to be in the way the key has been wrapped, though I could not find any errors. Where have I gone wrong?

0
1

Two problems that I can see.

1) You need to modify the index i in if(isupper(key[i]))) with modulo, similar to the way you do it in k=key[j%keylength]-'A';. Same goes for the islower statement that comes later.

2) Your index j should not increment every time. j should only increment when the char in the message is a letter. Try using isalpha to determine when not to increment the index.

You must log in to answer this question.

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