c - Vigenere Cipher Black Hawk Down -
i cannot figure out why thing doesn't scramble correctly. read other posts on cipher , far can tell i'm using exact same algorithm are...
the areas commented out tests tried make sure passing through correctly. believe goes through correctly fails in algorithm.
#include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> #include <stdlib.h> string get_message(void); string scramble(string key, string message); int main(int argc, string argv[]) { if(argc == 2) { string key; string message; key = argv[1]; //printf("key: %s<<",key); message = get_message(); scramble(key, message); } else { printf("please enter 2 arguments.\n"); return 1; } } string get_message(void) { string message = ""; { message = getstring(); } while(strlen(message) < 1); return message; } string scramble(string key,string message) { for(int = 0, len = strlen(message), key_len = strlen(key); < len; i++) { int letter = message[i]; //int tkey = atoi(key[i % key_len]); //printf("key: %d<<\n",tkey); if(islower(letter)) { //printf("key(%d)",(key[i % key_len]-97)); letter = (((letter - 97) + (key[i % key_len])) % 26 + 97); //printf("(%d)",(letter - 97) + (key[i % key_len])%26); printf("%c",letter); } else if(isupper(letter)) { //printf("(%d)", key[i]); //printf("(%c)",letter); have correct letter letter = (((letter - 65) + (key[i % key_len])) % 26 + 65); printf("%c",letter); } } printf("\n"); return 0; }
i think calculation wrong:
you have
encryptedletter = (letter - firstletteroffset) + key[position % keylength] % 26 + firstletteroffset
by check c operator precedence table notice %
evaluated before -
or +
, meaning code mean :
encryptedletter = (letter - firstletteroffset) + ( key[position % keylength] % 26 ) + firstletteroffset
where wanted :
encryptedletter = ( (letter - firstletteroffset) + key[position % keylength] ) % 26 + firstletteroffset
conclusion : need put more parenthese specify in order evaluate expression.
in addition took letter number text character not key !
correct expression
encryptedletter = ( (letter - firstletteroffset) + key[position % keylength] - firstletteroffset ) % 26 + firstletteroffset
Comments
Post a Comment