fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. // (a) アルファベットかどうかを判定する関数
  5. int isalphabet(char c) {
  6. return (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'));
  7. }
  8.  
  9. // (b) シーザー暗号の変換関数
  10. char caesar(char c, int n) {
  11. if (!isalphabet(c)) {
  12. return c; // アルファベットでなければそのまま返す
  13. }
  14.  
  15. int base = ('A' <= c && c <= 'Z') ? 'A' : 'a';
  16. int pos = c - base; // アルファベット内での位置(0〜25)
  17. int new_pos = (pos + n) % 26;
  18.  
  19. // 負のmod対策(C言語では -1 % 26 は -1 になるので)
  20. if (new_pos < 0) {
  21. new_pos += 26;
  22. }
  23.  
  24. return base + new_pos;
  25. }
  26.  
  27. // (c) メイン関数:暗号化と復号化のテスト
  28. int main() {
  29. char input[1000];
  30. int n;
  31.  
  32. printf("文字列を入力してください: ");
  33. fgets(input, sizeof(input), stdin);
  34. input[strcspn(input, "\n")] = '\0'; // 改行を削除
  35.  
  36. printf("シフト数を入力してください(例: 3): ");
  37. scanf("%d", &n);
  38.  
  39. // 暗号化
  40. char encrypted[1000];
  41. for (int i = 0; input[i] != '\0'; i++) {
  42. encrypted[i] = caesar(input[i], n);
  43. }
  44. encrypted[strlen(input)] = '\0';
  45.  
  46. printf("暗号化結果: %s\n", encrypted);
  47.  
  48. // 復号化
  49. char decrypted[1000];
  50. for (int i = 0; encrypted[i] != '\0'; i++) {
  51. decrypted[i] = caesar(encrypted[i], -n);
  52. }
  53. decrypted[strlen(encrypted)] = '\0';
  54.  
  55. printf("復号化結果: %s\n", decrypted);
  56.  
  57. return 0;
  58. }
  59.  
Success #stdin #stdout 0s 5284KB
stdin
stdout
文字列を入力してください: シフト数を入力してください(例: 3): 暗号化結果: え
復号化結果: え