Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- //26 letters in ASCII
- //cipher = 1st line. intercepted = 2nd line
- //check if char is a letter
- int isletter(char *cipher, char *intercepted)
- {
- for (int i = 0; cipher[i] != '\0'; i++)
- {
- if (!isalpha(cipher[i]))
- {
- return 1;
- }
- }
- for (int i = 0; intercepted[i] != '\0'; i++)
- {
- if (!isalpha(intercepted[i]))
- {
- return 1;
- }
- }
- return 0;
- }
- //compare length of cipher and intercepted
- int compare_length(char *cipher, char *intercepted)
- {
- for (int i = 0;; i++)
- {
- if (((cipher[i]) == '\0' && (intercepted[i]) != '\0') || ((intercepted[i]) == '\0' && (cipher[i]) != '\0'))
- {
- return 1;
- break;
- }
- else if (cipher[i] == '\0' && intercepted[i] == '\0')
- {
- return 0;
- break;
- }
- }
- }
- int main(int argc, char *argv[])
- {
- //load the cipher
- char *cipher;
- cipher = (char *)malloc(1 * sizeof(char));
- int counter = 0;
- while (1)
- {
- scanf("%c", cipher + counter);
- if (cipher[counter] == '\n')
- {
- cipher[counter] = '\0';
- break;
- }
- counter++;
- cipher = realloc(cipher, counter+1);
- }
- //load the intercepted text
- char *intercepted;
- intercepted = (char *)malloc(1 * sizeof(char));
- counter = 0;
- while (1)
- {
- scanf("%c", intercepted + counter);
- if (intercepted[counter] == '\n')
- {
- intercepted[counter] = '\0';
- break;
- }
- counter++;
- intercepted = realloc(intercepted, counter+1);
- }
- //error messages
- if (isletter(cipher, intercepted) == 1)
- {
- fprintf(stderr, "Error: Chybny vstup!\n");
- free(cipher);
- free(intercepted);
- return 100;
- }
- else if (compare_length(cipher, intercepted) == 1)
- {
- fprintf(stderr, "Error: Chybna delka vstupu!\n");
- free(cipher);
- free(intercepted);
- return 101;
- }
- //the thing for the Caesar cipher!
- int size_cipher = strlen(cipher)+1;
- counter = 0;
- char decrypted[size_cipher];
- //shift in alphabet
- for (int i = 0; i <= 52; i++)
- {
- //compare cipher and intercepted text
- int temp_counter = 0;
- for (int j = 0; cipher[j] != '\0'; j++)
- {
- if (cipher[j] == intercepted[j])
- {
- temp_counter += 1;
- }
- }
- //getting new decrypted message
- if (temp_counter >= counter)
- {
- counter = temp_counter;
- strncpy(decrypted, cipher, size_cipher);
- }
- //shift the cipher
- for (int k = 0; cipher[k] != '\0'; k++)
- {
- cipher[k] = cipher[k] + 1;
- if (cipher[k] == 123)
- {
- cipher[k] = 'A';
- }
- else if (cipher[k] == 91)
- {
- cipher[k] = 'a';
- }
- }
- }
- printf("%s\n", decrypted);
- //free the memory
- free(cipher);
- free(intercepted);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement