【发布时间】: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