string text = GetString();
//enters length of argv string into q
//converts string argv[1] into string key
string key = argv[1];
int klen = strlen(key);
int kposition = 0;
//loop through the characters in array "text"
for (int tposition = 0, n = strlen(text); tposition < n; tposition ++)
{
if isupper(key[kposition])
{
key[kposition] = ((key[kposition] - 'A') % klen) + 'A';
}
else if islower(key[kposition])
{
key[kposition] = ((key[kposition] - 'a') % klen) + 'a';
}
//determine if character is alphabetical
if (isalpha(text[tposition]))
{
//encrypt upper case characters
if (isupper(text[tposition]))
{
//modulo magic to loop to beginning of alphabet after 'Z'
text[tposition] = (((text[tposition] - 'A') + key[kposition]) % 26) + 'A';
printf("%c", text[tposition]);
}
//encrypt lower case characters
else
{
//modulo magic to loop to beginning of alphabet after 'z'
text[tposition] = (((text[tposition] - 'a') + key[kposition]) % 26) + 'a';
printf("%c", text[tposition]);
}
}
//if the input isn't alphabetical, then just print the input (spaces)
else
{
printf("%c", text[tposition]);
}
kposition ++;
}
printf("\n");
return 0;
}
I followed your advice and made my variables a bit more descriptive, which helps me look at the code.
I am still not getting the correct outputs from my program, though it compiles and runs fine.
For example, when I run: vigenere.c -bacon
and enter: "Meet me at the park", I get: "Gxzq mr ni kyr frea", rather than the correct answer, which is: "Negh zf av huf pcfx".
So the upper/lower case is working, and the spaces are working. The problem lies with the incrementing of key[kposition]. Part of the problem is that I don't intuit modulo very well, so it's not clear to me exactly what the modulo arithmetic is doing (other than it gives the remainder of the two numbers).
How can I arrange my key[kposition] incrementor better?