0

When i tested the program using the keyword "BaZ" from cs50 submit. It received "BaRFoo" and returned "CaRGog" as an output instead of "CaQGon"

string s;
s=GetString();
string key;
key=argv[1];
int a=strlen(key);
for(int n=0; n < strlen(key); n++)
{
    if(isupper(key[n]))
    {
        key[n] = (tolower(key[n])-'a');
    }
    else if(islower(key[n]))
    {
        key[n] = (key[n]-'a');
    }
    else
    {
        printf("error");
        return 0;
    }
}
int t=0;
for(int n=0; n < strlen(s); n++)
{
    int v = t%a;
    t++;
    if(s[n]>='A' && s[n]<='Z')
    {
        int o = (s[n] - 'A' + key[v]) % 26  +'A';
        printf("%c",(char) o);
    }
    else if(s[n]>='a' && s[n]<='z')
    {
         int o = (s[n] -'a'+ key[v]) % 26  + 'a';
         printf("%c",(char) o);
    }
    else
    {
        printf("%c",s[n]);
        t--;
    }

    }
printf("\n");
1

The problem lies in your for loop that converts the key from letters to numbers. It's a very subtle problem. Look at the for loop setup:

for(int n=0; n < strlen(key); n++)

The loop is going to continue until n is >= strlen(key), which is recalculated after each pass. But what determines strlen(key)?

The strlen() function looks for the end of string marker, represented by a byte of all zero bits. Here's where it gets interesting. When you do the conversion of each letter in the key, the letters are stored as 1 byte unsigned integers. This becomes a problem when you process an 'a'. That 'a' will be converted to 0, or hex 0x00, which happens to be the end of string marker. The loop will stop after processing the 'a' and the results after that become unpredictable (well, ok, predictable, but not good.)

The fix is to assign strlen(key) to a variable that will not change. You've already done this one line earlier. Use a to control the loop, not the strlen() function.

There may be other issues, but this should resolve your question. If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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