#include <stdio.h> #include <cs50.h> #include <string.h> #include <ctype.h> int main(int argc, string argv[]) { //string key = argv[1] if (argc !=2) { printf("Please, enter a normal key"); return 1; } else { int k = atoi(argv[1]) % 26; if(k == 0) { printf("It is a wrong key. Try one more time"); return 1; } string word = GetString(); if(word != NULL); { for (int i = 0, n = strlen(word); i < n; i++) { int c = 0; if(isupper(word[i])) { c = (((int)word[i] - 65 + k) % 26) + 65; printf("%c", (char)c); } else if(islower(word[i])) { c = (((int)word[i] - 97 + k) % 26) + 97; printf("%c", (char)c); } else printf("%c", word[i]); } printf("\n"); return 0; } } } 

 c = (((int)word[i] - 65 + k) % 26) + 65; c = (((int)word[i] - 97 + k) %26) + 97; 

    1 answer 1

    Ugly code. First note that A = 65 and a = 97, the number of characters in the alphabet = 26.

    Rewrite c = (((int)word[i] + k -'A') % ALPHABET_SIZE) + 'A'

    Already a little clearer, this is Caesar's cipher, a cyclic shift of the alphabet a few characters to the right.

    1 line - large letters, 2 - small.

    For example, when k = 3, we replace a->d b->e ... x->a y->b z->c

    • one
      There is also a memory leak - the buffer allocated for the word string is not freed. - zed
    • one
      Only the alphabet sounds better. - 0andriy