Guest User

Untitled

a guest
May 27th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. //Vigenere cipher created for CS50 intro to CS course
  2.  
  3.  
  4. #include <cs50.h>
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <string.h>
  8. #include <ctype.h>
  9.  
  10. int main(int argc, string argv[])
  11. {
  12. //Only accept one key word. No more no less.
  13. if (argc !=2)
  14. {
  15. printf("Gimmie ONE key\n");
  16.  
  17. return 1;
  18. }
  19.  
  20. //No numbers allowed in key word
  21. else
  22. {
  23. for (int i = 0, n = strlen(argv[1]); i < n; i++)
  24. {
  25. if (isdigit(argv[1][i]))
  26. {
  27. printf("No numbers! Geez!\n");
  28.  
  29. return 1;
  30. }
  31. }
  32. }
  33.  
  34. string k = argv[1];
  35.  
  36. string p = get_string("Input plaintext: ");
  37.  
  38. printf("ciphertext: ");
  39.  
  40. for (int i = 0, j = 0, n = strlen(p), klength = strlen(k); i < n; i++)
  41. {
  42. //check if plaintext character is a letter
  43. if (isalpha(p[i]))
  44. {
  45. //check if plaintext character is lowercase
  46. if (islower(p[i]))
  47. {
  48. //Check if cipher character is lowercase and make a = 0, b = 1, etc if so.
  49. if (islower(k[j]))
  50. {
  51. printf("%c", (((p[i] + ((k[j] - 97) % 26) - 97) % 26) + 97));
  52. }
  53. //If cipher character is uppercase, make A = 0, B = 1, etc.
  54. else
  55. {
  56. printf("%c", (((p[i] + ((k[j] - 65) % 26) - 97) % 26) + 97));
  57. }
  58. }
  59. //Same as above but for uppercase plaintext character
  60. else
  61. {
  62. if (islower(k[j]))
  63. {
  64. printf("%c", (((p[i] + ((k[j] - 97) % 26) - 65) % 26) + 65));
  65. }
  66. else
  67. {
  68. printf("%c", (((p[i] + ((k[j] - 65) % 26) - 65) % 26) + 65));
  69. }
  70. }
  71. //loop through cipher key
  72. j = (j + 1) % klength;
  73. }
  74. //Simply print character if non-alpha
  75. else
  76. {
  77. printf("%c", p[i]);
  78. }
  79. }
  80. printf("\n");
  81. }
Add Comment
Please, Sign In to add comment