0

I've been working on this for a while now. And I get it to work as long as I use lowercase letters. But when I try uppercase, they double and everything goes south.. Please help!_ Here is my code!

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

int main (int argc, string argv[])

{

if (argc != 2)
{

printf("The comandline argument is not correct. Please enter one word\n");
return 1;
}

string key = argv[1];

for (int i = 0; i < strlen(argv[1]); i++)
{

if (!isalpha(key[i]))
{
printf("Please use alphabetical characters only\n");
return 1;
}
}

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

key[i] = tolower(key[i]);
}

printf("Please enter a text to encrypt\n");
string txt = GetString();

int j = 0;
for (int i = 0; strlen(txt) >= i ; i++)
{

if (j >= strlen(key))
{

j = 0;
}
    if (isalpha(txt[i]))
    {

        if (isupper(txt[i]))
        {

            int c = (txt[i] - 'a' + key[j] - 'a') % 26 + 'a';
            printf("%c",c);
        }

        else if (islower(txt[i]));
        {
            int l = (txt[i] - 'a' + key[j] - 'a') % 26 + 'a';
            printf("%c",l);
        }  

    j++;

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

}

printf("\n");

}
1

I would bet that you've been looking at this so much that everything seems right. Can't see the forest for the trees. You have several syntax errors in your code.

First, look at the test in this for loop.

for (int i = 0; strlen(txt) >= i ; i++)

You are going past the end of txt.

Second, look at this:

    if (isupper(txt[i]))
    {
        int c = (txt[i] - 'a' + key[j] - 'a') % 26 + 'a';

txt[i] is upper case, but you are subtracting lowercase a.

Third, what doesn't belong in this line?

    else if (islower(txt[i]))     ;

These problems could be spotted with the addition of a few simple printf codes to show the path through the code that is being followed. Or, you could have traced through it with gdb. Debugging is a talent that takes a lot of practice and exposure. Stick with it!

If this answers your question, please accept this answer to remove the question from the unanswered question pool. Let's keep up on forum housekeeping. ;-)

You must log in to answer this question.

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