Advertisement
UME14

CS50/PSET2/vigenere

Jan 2nd, 2019
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <ctype.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. int main(int argc, string argv[])
  8. {
  9. string keyString;
  10. if (argc == 2)
  11. {
  12. keyString = argv[1];
  13. if (!isalpha(keyString[0]))
  14. {
  15. return 1;
  16. }
  17. }
  18. else
  19. {
  20. return 1;
  21. }
  22.  
  23. int keyLength = strlen(keyString);
  24. string pt = get_string("Enter text: ");
  25. char ct[strlen(pt) + 2];
  26.  
  27. char chaesarChar (char alpha, char key);
  28.  
  29. int keyIndex = 0;
  30.  
  31.  
  32. for (int i = 0, n = strlen(pt); i < n; i++)
  33. {
  34. //index
  35. int index = keyIndex % keyLength;
  36. //taken, plaintext is a word
  37. if (isalpha(pt[i]))
  38. {
  39. if (isupper(pt[i]))
  40. {
  41. ct[i] = chaesarChar(pt[i], keyString[index]);
  42. if (ct[i] > 90)
  43. {
  44. ct[i] -= 26;
  45. }
  46. }
  47. else if (islower(pt[i]))
  48. {
  49. ct[i] = chaesarChar(pt[i], keyString[index]);
  50. if (ct[i] > 122)
  51. {
  52. ct[i] -= 26;
  53. }
  54. }
  55. }
  56. else
  57. {
  58. ct[i] = pt[i];
  59. }
  60.  
  61. keyIndex += 1;
  62.  
  63. ct[strlen(pt) + 1] = '\0';
  64.  
  65. printf("%s\n", ct);
  66.  
  67. return 0;
  68. }
  69.  
  70. char chaesarChar (char alpha, char key)
  71. {
  72. char x = key;
  73. if (islower(key)){
  74. x = key - 97;
  75. }
  76. else if (isupper(key))
  77. {
  78. x = key - 'A';
  79. }
  80. char res = alpha + x;
  81.  
  82. return res;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement