Advertisement
wyx0311

caesar_segmentation_fault1

Mar 28th, 2024
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.51 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.     for (int j = 0, n = strlen(s); j < n; j++)
  53.     {
  54.         if (!isdigit(s[j]))
  55.         {
  56.             printf("Usage: ./caeser key\n");
  57.             return 1;
  58.         }
  59.     }
  60.     return 0;
  61. }
  62.  
  63. int string_to_int(string s)
  64. {
  65.     int m;
  66.     m = atoi(s);
  67.     return m;
  68. }
  69.  
  70. char rotate(char c, int h)
  71. {
  72.     int cc;
  73.     if(isalpha(c))
  74.     {
  75.         if(isupper(c))
  76.         {
  77.             cc = c - 'A';
  78.             int k = (cc + h) % 26;
  79.             c += k;
  80.         }
  81.         else
  82.         {
  83.             cc = c - 'a';
  84.             int k = (cc + h) % 26;
  85.             c += k;
  86.         }
  87.         return c;
  88.     }
  89.     else
  90.     {
  91.         return c;
  92.     }
  93. }
  94.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement