Last active
May 29, 2020 02:00
-
-
Save wx5162839/e1f3e780b21a0d91d988d3d5bf7cf285 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <cs50.h> | |
| #include <ctype.h> | |
| #include <string.h> | |
| int main(int argc, char *argv[]) | |
| { | |
| if (argc != 2) | |
| { | |
| printf("Usage: ./substitution key\n"); | |
| return 1; | |
| } | |
| // argv is a list of strings (ie. char **) | |
| // argv is an array of strings, or say, an array of char *. So the type of argv[1] is char *, and the type of argv[1][0] is char. | |
| // https://stackoverflow.com/questions/21136735/store-argv1-to-an-char-variable | |
| for (int k = 0; k < strlen(argv[1]); k++) | |
| { | |
| if (!isalpha(argv[1][k])) | |
| { | |
| printf("Usage: ./substitution key\n"); | |
| return 1; | |
| } | |
| } | |
| if (strlen(argv[1]) != 26) | |
| { | |
| printf("Key must contain 26 characters.\n"); | |
| return 1; | |
| } | |
| // Check all characters are different in a string. | |
| for (int i = 0; i < 26; i++) | |
| { | |
| for (int j = i + 1; j < 26; j++) | |
| { | |
| if (tolower(argv[1][i]) == tolower(argv[1][j])) | |
| { | |
| printf("has same characters.\n"); | |
| return 1; | |
| } | |
| } | |
| } | |
| char *p = get_string("plaintext: "); | |
| int x = 0; | |
| // Why? https://www.reddit.com/r/cs50/comments/gryswz/please_help_i_get_a_segmentation_fault_in/ | |
| char *y = malloc(sizeof(p) * sizeof(char) + 1); | |
| for (int a = 0, n = strlen(p); a < n; a++) | |
| { | |
| if (isalpha(p[a])) | |
| { | |
| x = tolower(p[a]) - 'a'; | |
| if (islower(p[a])) | |
| { | |
| y[a] = tolower(argv[1][x]); | |
| } | |
| if (isupper(p[a])) | |
| { | |
| y[a] = toupper(argv[1][x]); | |
| } | |
| } | |
| else | |
| { | |
| y[a] = p[a]; | |
| } | |
| } | |
| printf("ciphertext: %s\n", y); | |
| free(y); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment