Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cs50.h>
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- int main(int argc, string argv[])
- {
- int KEY = 0;
- bool NUM = true;
- int j = 0;
- //checks if there are 2 args entered
- if (argc == 2)
- {
- j = strlen(argv[1]);
- }
- else
- {
- //explains useage if argv1 was not correctly entered
- printf("Usage: ./cesar key\n");
- return 1;
- }
- //checks if argv[1] is a number
- for (int i = 0; i < j; i++)
- {
- if (isdigit(argv[1][i]))
- {
- NUM = true;
- }
- else
- {
- NUM = false;
- break;
- }
- }
- //only runs main program if all checks above are true (argv[1] is a number and there is only 2 args entered)
- if (NUM == true)
- {
- string plain = (get_string("Enter your plaintext: \n"));
- //converts argv[1] to int
- for (int i = 0, n = strlen(argv[1]); i < n; i++)
- {
- KEY = KEY * 10 + (int) argv[1][i] - '0';
- }
- //reduces the key smallest necessary integer. Over 26 loops around extra.
- while (KEY > 26)
- {
- KEY = KEY - 26;
- }
- //iterates over the length of the plaintext string
- for (int i = 0, n = strlen(plain); i < n; i++)
- {
- //checks if the character is uppercase
- if (plain[i] >= 'A' && plain[i] <= 'Z')
- {
- //checks that the character plain[i] + the key remains within the uppercase letters in ASCII
- char c = plain[i] + KEY;
- if (c >= 'A' && c <= 'Z')
- {
- printf("%c", c);
- }
- //if plain[i] + key is higher than 'Z' it will remove '26' to bring it back within confines of A through Z
- else
- {
- c = c - 26;
- printf("%c", c);
- }
- }
- //checks if the character plain[i] is a lowercase letter
- else if (plain[i] >= 'a' && plain[i] <= 'z')
- {
- //checks that the character plain[i] + the key remains within the lowercase letters in ASCII
- char c = plain[i] + KEY;
- if (c >= 'a' && c <= 'z')
- {
- printf("%c", c);
- }
- else
- {
- //if plain[i] + key is higher than 'z' it will remove '26' to bring it back within confines of a through z
- c = c - 26;
- printf("%c", c);
- }
- }
- //if character is not a letter, just prints the character as is
- else
- {
- printf("%c", plain[i]);
- }
- }
- //writes a new line for cleanliness at the end
- printf("\n");
- return 0;
- }
- else
- {
- //explains useage if argv1 was not correctly entered
- printf("Usage: ./cesar key\n");
- return 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement