Advertisement
wyx0311

caesar_segmentation_fault

Mar 28th, 2024
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | Source Code | 0 0
  1. #include <cs50.h>
  2. #include <ctype.h>
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <stdlib.h>
  6.  
  7. bool count_argv(int argc);
  8.  
  9. bool only_digits(string s);
  10.  
  11. int string_to_int(string s);
  12.  
  13. char rotate(char c, int h);
  14.  
  15. int main(int argc, string argv[])
  16. {
  17.     bool n1 = count_argv(argc);
  18.  
  19.     bool n2 = only_digits(argv[1]);
  20.  
  21.     const int key = string_to_int(argv[1]);
  22.  
  23.     if (n1 == 0 && n2 == 0)
  24.     {
  25.         string text = get_string("plaintext: ");
  26.  
  27.         printf("ciphertext: ");
  28.  
  29.         for (int i = 0, n = strlen(text); i < n; i++)
  30.         {
  31.             printf("%c", rotate(text[i], key));
  32.         }
  33.         printf("\n");
  34.     }
  35. }
  36.  
  37. bool count_argv(int argc)
  38. {
  39.     if (argc != 2)
  40.     {
  41.         printf("Usage: ./caeser key\n");
  42.         return 1;
  43.     }
  44.     else
  45.     {
  46.         return 0;
  47.     }
  48. }
  49.  
  50. bool only_digits(string s)
  51. {
  52.     int j = 0;
  53.     do
  54.     {
  55.         j++;
  56.     }
  57.     while (isdigit(s[j]));
  58.     int t = strlen(s);
  59.     if (j == t)
  60.     {
  61.         return 0;
  62.     }
  63.     else
  64.     {
  65.         printf("Usage: ./caesar key\n");
  66.         return 1;
  67.     }
  68. }
  69.  
  70. int string_to_int(string s)
  71. {
  72.     int m;
  73.     m = atoi(s);
  74.     return m;
  75. }
  76.  
  77. char rotate(char c, int h)
  78. {
  79.     int cc;
  80.     if(isalpha(c))
  81.     {
  82.         if(isupper(c))
  83.         {
  84.             cc = c - 'A';
  85.             int k = (cc + h) % 26;
  86.             c += k;
  87.         }
  88.         else
  89.         {
  90.             cc = c - 'a';
  91.             int k = (cc + h) % 26;
  92.             c += k;
  93.         }
  94.         return c;
  95.     }
  96.     else
  97.     {
  98.         return c;
  99.     }
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement