natezomby

caesar attempt

Jan 14th, 2022 (edited)
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #include <cs50.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5.  
  6. bool only_digits(string s);
  7. int rotate(string text, int k);
  8. int atoi(string t);
  9.  
  10. int main(int argc, string argv[])
  11. {
  12. //Command line gets a user input of an int, error code if other input given than a single arg
  13. if (argc != 2)
  14. {
  15. printf("Usage: ./caesar key\n");
  16. return 1;
  17. }
  18. //Check if digits
  19. if (only_digits(argv[1]) == false)
  20. {
  21. printf("Usage: ./caesar key\n");
  22. return 1;
  23. }
  24. //else
  25. //{
  26. //printf("Works! \n");
  27. //}
  28. int key;
  29. key = atoi(argv[1]);
  30.  
  31. //Program prompts user for text input
  32. string ptext = get_string("Plaintext: \n");
  33.  
  34. //Run function that uses text input as array and replaces letters by a number of positions (int from command line) in alphabet array
  35. rotate(ptext, key);
  36.  
  37. //print new coded message
  38. }
  39.  
  40. bool only_digits(string s)
  41. {
  42. int digits = 0;
  43. int n = strlen(s);
  44. for (int i = 0; i < n; i++)
  45. {
  46. if (isdigit(s[i]))
  47. {
  48. digits++;
  49. }
  50. }
  51. if (digits == n)
  52. {
  53. return true;
  54. }
  55. else
  56. {
  57. return false;
  58. }
  59. }
  60.  
  61. int rotate(string text, int k)
  62. {
  63. printf("ciphertext: ");
  64. for (int i = 0, n = strlen(text); i < n; i++)
  65. {
  66. if (!isalpha(text[i]))
  67. {
  68. printf("%c", text[i]);
  69. }
  70. else if (isupper(text[i]))
  71. {
  72. printf("%c", ((((text[i] - 65) + k) % 26) + 65));
  73. }
  74. else if (islower(text[i]))
  75. {
  76. printf("%c", ((((text[i] - 97) + k) % 26) + 97));
  77. }
  78. else
  79. {
  80. printf("Something went wrong.");
  81. }
  82. }
  83. printf("\n");
  84. return 0;
  85. }
Add Comment
Please, Sign In to add comment