Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 65-90 A-Z, 97-122 a-z , upper 32 apart from lowercase
- //Declare pre-processor directives
- #include <cs50.h>
- #include <stdio.h>
- #include <ctype.h>
- #include <string.h>
- #include <stdlib.h>
- //Declare caesar cipher function
- char encipher(char cae, int k);
- //// (1) inline comments are actually a kind of "code" smell
- //// if you follow some guidelines, like using speaking variable names and use functions where possible to keep your main and other functions small,
- //// your code should be easy to understand, so no comments are needed
- //Declare main function
- int main(int argc, string argv[])
- {
- //Declare variables
- //// (2) always use "speaking" variable names
- string p;
- //// int n; see (4)
- /////if-else to check for 2 valid command line arguments (0-1)
- if (argc == 1)
- {
- printf("You entered no command line arguments, exiting the program\n");
- return 1;
- }
- // (3) else if not needed here
- if (argc > 2)
- {
- printf("Only one positive integer is accepted, exiting the program\n");
- return 1;
- }
- //Convert string argv[1] to int and initialize the value to variable k
- ////same as (2)
- int k = atoi(argv[1]);
- //Do-while loop until user enters valid string
- //// (4) put variables as close as possible where needed
- /// int n; actually not needed at all, see (5)
- do
- {
- p = get_string("plaintext: ");
- }
- while (strlen(p) == 0); //// (5)
- //// (6) could be extracted into a function
- //For loop to encipher text
- for (int i = 0; i < n; i++)
- {
- p[i] = encipher(p[i], k);
- }
- //print output
- printf("ciphertext: %s\n", p);
- //return error code of 0
- return 0;
- }
- //Caesar Cipher
- char encipher(char cae, int k) ////same as (2)
- {
- //Check if alphabetical
- if (isalpha(cae))
- {
- //Check if lowercase
- if (islower(cae))
- {
- cae = ((cae - 'a') + k) % 26 + 'a';
- }
- //Check if uppercase
- else if (isupper(cae))
- {
- cae = ((cae - 'A') + k) % 26 + 'A';
- }
- }
- return cae;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement