1

The following is my code, I'm not sure where I went wrong with my code, but when I run it, it seems to work for lower case letters but not uppercase. This isn't the full code, due to academic honesty, but I think the problem is in this section.

int main(int argc, string argv[]) { int KeyValue, change, result, KeyLength;

string text= GetString();

for(int i=0, j=0, length = strlen(text); i<length; i++, j++)
{
    if(j>= strlen(key))
    {
        j=0;
    }

    KeyValue = key[j];

    if(!isalpha(text[i]))
    {
        j=(j-1);
    }

    if((KeyValue>=65)&&(KeyValue<=90))
    {
        KeyValue = (KeyValue - 65);
    }

    if((KeyValue>=97)&&(KeyValue<=122))
    {
        KeyValue = (KeyValue - 97);
    }

    change = (text[i] + KeyValue);

    if(isalpha(text[i]))
    {
        if(isupper(text[i]))
        {
            result=(((text[i] - 65) + (key[j%KeyLength]-65))%26)+65 ;
            printf("%c", result);
        }

        else if(islower(text[i]))
        {
            text[i]=(((text[i] - 97) + (key[j%KeyLength]-97))%26)+97 ;
            printf("%c", text[i]);
        }

    }
    else
    {
        printf("%c", text[i]);
    }

}
printf("\n");
return 0;

}

2 Answers 2

2

There are a couple of problems. The main one is that your code doesn't handle the case where the plain text and the key characters are not the same case. It assumes that if the plain text is lower case, then so is the key. Same for upper case.

The three remaining problems are related - no error handling for command line inputs. The code should generate an error if there is no parameter, if there's more than 1 parameter, or if the key contains a non-alpha, as specified in the pset.

It looks like you started down one design path, by the calculation of change, but then abandoned it for another design in the code that follows. Code that serves no purpose should be removed.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

0

Well why don't you try to print it the same way as the lower case? Instead you are using an int called result and trying to print it as a character.

1
  • I tried, and it still doesn't work. When I run it through check50 it gives me :) 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 :( encrypts "BaRFoo" as "CaQGon" using "BaZ" as keyword \ expected output, but not "CaQGoh\n" :) encrypts "BARFOO" as "CAQGON" using "BAZ" as keyword :) handles lack of argv[1] :) handles argc > 2 :) rejects "Hax0r2" as keyword
    – EmmaDB
    Commented Jun 15, 2016 at 20:49

You must log in to answer this question.

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