0

I've searched and find similar questions but I think my problem is different. If not sorry in advance for duplicate question.

I manually test every case check50 tests and my code gives me the correct answers. What am I missing?

My check50 results: https://cs50.me/checks/1c14dab8a805c881828f02037ad44c913a2e7baa

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


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

// plaintext (but at some point it becames ciphertext)
string pt;



// checking the number of arguments and if they are alphabetical
if (argc > 2 || argc < 2)
{
    printf("Please enter one key!\n");
    return 1;
}

// key word
string k = argv[1];

// storing this lenght here before it becomes 0 in some cases
int klen = strlen(k);

for (int i = 0; i < klen; i++)
{
    if (!isalpha(k[i]))
    {
        printf("Please enter an alphabetical key!\n");
        return 1;
    }

}

// prompting for pt
pt = get_string("plaintext: ");

// making key usable by omitting the difference between ascii value and alphabet index
for (int i = 0; i < klen; i++)
{
    if (isupper(k[i]))
    {
        k[i] = k[i] - 65;
    }

    if (islower(k[i]))
    {
        k[i] = k[i] - 97;
    }
}

// counts every time key word is used
int j;

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

    // not to exceed keywords' length
    j = (j % klen);

    if (isalpha(pt[i]))
    {
        if (isupper(pt[i]))
        {
            pt[i] = pt[i] - 65;
            pt[i] = (pt[i] + k[j]) % 26 + 65;
        }
        if (islower(pt[i]))
        {
            pt[i] = pt[i] - 97;
            pt[i] = (pt[i] + k[j]) % 26 + 97;
        }

        // incrementing j only if a letter is changed
        j++;

    }

}

printf("ciphertext: %s\n", pt);

return 0;

}

1 Answer 1

1

A really strange problem, everything is the fault of the following statement:

int j;

We have not initialized the variable j, after using gdb j it is set to zero inside the following statement:

j = (j % klen);

and your program works well the IDE, but for some reason this does not happen with check50, as it should be since j has an undefined value, so check50 fails. Your problem has a solution if you do:

int j = 0;
2
  • Thanks a lot. That solved my problem. But I didn't still understand why it worked in IDE.
    – ebrar
    Commented May 21, 2018 at 21:10
  • I hope that someone with more knowledge can explain it convincingly
    – MARS
    Commented May 21, 2018 at 21:47

You must log in to answer this question.

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