I've been busting my head over this all day. So the main problem (I think) is that I'm having difficulties synchronizing the chars from the key with the chars from the sentence after a non-alpha character is on the way. The problem is that int "i" (in the code in this post) keeps going up even when there are non-alpha characters, so in my equation later, the key also moves one position away from the letter that should be used. That's why I created "o" which should increase every time the programme gets to a non-alphabetic character. Then its value gets subtracted and that way cuts the gap between the two strings (key and sentence). That was a brief explanation on the most important point in my code from where I think the problem comes. I hope that any of you guys would give me a tip on how to fix my loop, offer other non-loop solutions or finds a different problem in the code.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[])
{
while(argc != 2) //yells at the user if more or less than 2 arguments
{
printf("Enter a key.\n");
return 1;
}
string s = GetString(); //user gives input
for(int i = 0, n = strlen(s); i < n; i++) //goes through every character of that input
{
for(int o = 0; isalpha(s[i]); o++) //loop used to cope with dishronyzation because of non-alpha chars
{
if(isalpha(s[i])) //checks if its a letter character
{
o = o - 1; //getting rid of "o" value because the char is a letter
int d = strlen(argv[1]);
if(isupper(s[i])) //checks if its an uppercase letter
{
int f = (i - o) % d; //synchronizes every character from the key with every character from the sentence
int h = argv[1][f] - 65; //because of "o", excluding the difference that non-alpha chars give
char v = s[i] - 65;
char a = (v + h) % 26; //uses modulo, so that the output is only alphabetical
char l = a + 65;
printf("%c", l); //prints the encrypted character
}
if(islower(s[i])) //does the same process for lowercase letters
{
int w = (i - o) % d;
int e = argv[1][w] - 97;
char t = s[i] - 97;
char y = (t + e) % 26;
char u = y + 97;
printf("%c", u);
}
}
else
{
printf("%c", s[i]); //prints non-alpha chars
}
}
}
printf("\n");
}