【问题标题】:Simple Ceasar Cipher in CC语言中的简单凯撒密码
【发布时间】:2014-11-06 22:50:40
【问题描述】:

我正在用 C 语言编写一个简单的 Ceasar Cipher 加密程序。我试图让我和我儿子更容易破译,所以我制定了以下规则:字母以外的字符保持不变,而小写和大写将保留在他们当前的情况(因此 Y 增加 3 将返回到 B)。密钥和短语将仅使用单独的文件(我的秘密!)进行管道传输,尽管其内容示例如下:

4 
This line of text will be encrypted.

我想使用 getchar 和 putchar 逐个字符地缓冲它,这样我就不必为长度总是未知的数组而烦恼。如何检查字符是大写字母还是小写字母,并通过他们给定的键递增它,同时保持与前面的规则一致。 putchar 应该在循环内以缓冲它吗?这是我当前的代码

#include <stdio.h>  
int main() { 

   int shift; 
   char msgIn, msgOut;

   // space after to keep is from terminating immediately
   scanf("%d ", &shift);
   msgIn = getchar();

   //increment current character and output until newline
   while (msgIn != '\n') {
     //check for upper or lower, else do nothing
     if((msgIn >= 'A') && (msgIn <= 'Z')) {
        msgOut = msgIn + shift; //increment current character, not sure how to handle this better 
        }
     //checking for lower case 
     else if((msgIn >= 'a') && (msgIn <= 'z')) {
        msgOut = msgIn + shift; //increment current character 
        }
     } 

     putchar(msgOut); //output incremented character
   }

   return 0; 
} 

____ 修改代码

do {
    msgIn = getchar();

    if((msgIn >= 'A') && (msgIn <= 'Z')) {
        putchar(((msgIn - 'A') + shift) % 26 + 'A'); 
        }
    else if((msgIn >= 'a') && (msgIn <= 'z')) {
        putchar(((msgIn - 'a') + shift) % 26 + 'a'); 
        }
    } 
} while (msgIn != '\n');

在您的帮助下,我认为这个修改后的代码会做得最好,尚未测试,但它看起来可以处理循环、输入、检查 ascii 大小写、处理环绕和输出。

【问题讨论】:

  • 搜索[c] Ceasar Cipher
  • 我不明白你“不使用额外功能”的理由——这似乎是一种非常糟糕的做法,并没有让任何事情变得“更简单”。
  • 这不是 Objective-C 代码;请不要再添加该标签。
  • 这个程序只有一个指令,对于一个复杂到只做一件简单事情的程序来说,不需要使用额外的函数。
  • 请注意,您只在循环外调用getchar() 一次。您将希望在循环内部调用它,而不是在外部调用它,否则您将永远不会读到消息的第一个字符。

标签: c encryption ascii


【解决方案1】:

请记住,您希望将大写字母保持为大写,那么当您移动“Z”时会发生什么?

查看modulo 运算符% 以提供帮助。

if (msgIn >= 'A' && msgIn <= 'Z') {
    msgOut = 'A' + (msgIn - 'A' + shift) % ('Z' - 'A' + 1);
}

这是一些大写字母大小写的代码,会导致字母环绕。 'Z' + 3 变成 'C' 等等。

【讨论】:

  • 我在想类似的事情(虽然你的 msgIn 和 out 似乎关闭了),更像是这样:msgOut = ((msgIn - 'A') + shift) % 26 + 'A';
【解决方案2】:

我猜你所说的简单是指你儿子容易理解?你可以 使用 switch 语句或条件,但为了简单起见,这是一种解决方案。

 shift = 0;     
 if (msgIn>64 && msgIn< 88) shift = 3;
 if (msgIn>87 && msgIn< 90) shift = -23;     

 if (msgIn>64 && msgIn< 120) shift = 3;     
 if (msgIn>119 && msgIn< 123) shift = -23;     

【讨论】:

  • 你觉得Magic numbers更容易理解?
  • 哪个孩子不知道 ASCII 字符 - 开个玩笑。是的,字符更好。
猜你喜欢
  • 2014-02-28
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多