something weird is going on with my code. I get the first word ("Meet" with key "bacon") right, but after that, things are getting really hairy. here is my code. I would really apreciate any help, I've been sitting on this problem for days already.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main (int argc, string argv[])
{
string key = "input";
if (argc != 2)
{
printf ("please provide only one keyword (alphabetical)\n");
return 1;
}
else if(argv[1])
{
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (!isalpha (argv[1][i]) )
{
printf ("Please only letters in the keyword!\n");
return 1;
}
else
{
key = argv[1];
}
}
}
string p = GetString();
int m_length = strlen(p);
int k_length = strlen(key);
for (int i = 0; i < m_length; i++)
{
if (isalpha(p[i]))
{
if (islower(p[i]))
{
printf("%c", (((p[i] - 97) + ((key[(i % k_length)]) - 97)) % 26 + 97));
}
else
{
printf("%c", (((p[i] - 65) + (toupper((key[(i % k_length)])) - 65) % 26) + 65));
}
}
else
{
printf("%c", p[i]);
}
}
}
UPDATE: Thanks Cliff, I realized i also need to add "tolower" in order to handle the upper case key chars with lower case message chars. The code works now, but only without the spaces between the words. I want to just print them, but somehow the program doesn't handle it properly. Any thoughts?
for (int i = 0; i < m_length; i++)
{
if (isalpha(p[i]))
{
if (islower(p[i]))
{
printf("%i ", ( (p[i]-97) + (tolower(key[(i%k_length)]) - 97) ) % 26 + 97);
}
else
{
printf("%i ", ( (p[i]-65) + (toupper(key[(i%k_length)]) - 65) ) % 26 + 65);
}
}
else
{
printf("%c", p[i]);
}
}