I got it working, maybe this will help somebody else. I'll detail my reasoning, so please correct me if anything is wrong.
In my code above I had written: (plain[i]-65) + k) % 26); as a way of converting from ASCII values to the alphabetical index. This seems to be correct. Using the letter M for example with an ASCII value of 77. So, 77 - 65 = 12. And the ...
I am among those people who suggest you to use 2 loop variables, actually its 1. Use a variable (say i) to iterate over each element of the input string and maintain another variable (say j) to hover over the key in the same loop. Consider the string to be array, then to eliminate wrapping over non-alphabetical characters, do the following in loop.
In this code, you see how you subtracted 'a' from the plaintext?
int f = plaintext[c] - 'a';
plaintext[c] = ((f + input[e]) % 26) + 'a';
input[e] still contains an ASCII value. Want to guess what impact that has?
Next, you've tied the index for the key directly to the password. What happens when non-alphas are processed? The key ...
if (j % (strlen(argv) - 1) == 0)
Why are you subtracting 1? That deals with correcting the reset to 0.
However, there is a serious logic problem in the code. Simply put, nested for loops simply don't work here. It will end up going through the plain text j times (it could also potentially turn into an infinite loop when j is reset to 0). The code needs ...
After the first pass through the key, every char in the key has been converted to numbers between 0 and 25 inclusive. Starting on the second pass through, the else clauses are executing, moving the key values into negative numbers. The results now become garbage.
The concept of converting the key to numbers from 0 to 25 is good. You just need to do it only ...
When I did this (yesterday) I obtained the string length of the key, then obtained the modulus of the length of the key.
j % lengthOfKeyVariable
then I incremented j, as long as you don't reset J within the for loop it should allow you to select the correct char of the string
It probably works fine with 1, but the rest is an accurate description of what is happening. Your problem is here:
char ciphertext = 'a' + ((plaintext[i] + key) % 26);
Try plugging the actual numbers into this. Say that plaintext[i] is 'a' and key is 27. Here's what happens:
'a' + ((plaintext[i] + key) % 26)
= 97 + (( 97 + 27 ) % 26 )
= 97 + (( 124 ) % ...
another way to do it
j = j % v;
where j is the jth char of key and v is strlen of key. when placed at the end of your shift functions within your if statement, j will increment only when you've executed your shift functions. so if plaintext[i] is not alpha it doesn't increment.
as opposed to
j = i % v;
while it will wrap, it increments j ...