Advertisement
Guest User

Untitled

a guest
Mar 20th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. // 65-90 A-Z, 97-122 a-z , upper 32 apart from lowercase
  2. //Declare pre-processor directives
  3. #include <cs50.h>
  4. #include <stdio.h>
  5. #include <ctype.h>
  6. #include <string.h>
  7. #include <stdlib.h>
  8.  
  9. //Declare caesar cipher function
  10. char encipher(char cae, int k);
  11.  
  12.  
  13. //// (1) inline comments are actually a kind of "code" smell
  14. //// if you follow some guidelines, like using speaking variable names and use functions where possible to keep your main and other functions small,
  15. //// your code should be easy to understand, so no comments are needed
  16.  
  17. //Declare main function
  18. int main(int argc, string argv[])
  19. {
  20. //Declare variables
  21. //// (2) always use "speaking" variable names
  22. string p;
  23. //// int n; see (4)
  24.  
  25. /////if-else to check for 2 valid command line arguments (0-1)
  26. if (argc == 1)
  27. {
  28. printf("You entered no command line arguments, exiting the program\n");
  29. return 1;
  30. }
  31.  
  32. // (3) else if not needed here
  33. if (argc > 2)
  34. {
  35. printf("Only one positive integer is accepted, exiting the program\n");
  36. return 1;
  37. }
  38.  
  39. //Convert string argv[1] to int and initialize the value to variable k
  40. ////same as (2)
  41. int k = atoi(argv[1]);
  42.  
  43. //Do-while loop until user enters valid string
  44.  
  45. //// (4) put variables as close as possible where needed
  46. /// int n; actually not needed at all, see (5)
  47. do
  48. {
  49. p = get_string("plaintext: ");
  50. }
  51. while (strlen(p) == 0); //// (5)
  52.  
  53. //// (6) could be extracted into a function
  54. //For loop to encipher text
  55. for (int i = 0; i < n; i++)
  56. {
  57. p[i] = encipher(p[i], k);
  58. }
  59.  
  60. //print output
  61. printf("ciphertext: %s\n", p);
  62.  
  63. //return error code of 0
  64. return 0;
  65. }
  66.  
  67. //Caesar Cipher
  68. char encipher(char cae, int k) ////same as (2)
  69. {
  70. //Check if alphabetical
  71. if (isalpha(cae))
  72. {
  73. //Check if lowercase
  74. if (islower(cae))
  75. {
  76. cae = ((cae - 'a') + k) % 26 + 'a';
  77. }
  78.  
  79. //Check if uppercase
  80. else if (isupper(cae))
  81. {
  82. cae = ((cae - 'A') + k) % 26 + 'A';
  83. }
  84. }
  85.  
  86. return cae;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement