我正在C中使用一個簡單的Ceasar密碼加密程序。我試圖讓我的兒子和我更容易解密,所以我把這些規則:字母以外的字符保持不變,而小寫並且大寫字母將保留在他們當前的情況下(所以Y增加3會回到B)。密鑰和短語將只使用一個單獨的文件通過管道輸送,雖然它的一個樣本的含量將是(我的祕密!):C中的簡單Ceasar密碼
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大小寫,處理環繞和輸出。
搜索'[E] Ceasar Cipher' – BLUEPIXY 2014-11-06 22:56:54
我不明白你對「不使用額外功能」的推理 - 這似乎是非常糟糕的做法,並沒有使任何「更簡單」。 – 2014-11-06 22:58:11
這不是Objective-C代碼;請不要再添加該標籤。 – 2014-11-06 23:04:30