2014-11-06 29 views
0

我正在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大小寫,處理環繞和輸出。

+1

搜索'[E] Ceasar Cipher' – BLUEPIXY 2014-11-06 22:56:54

+0

我不明白你對「不使用額外功能」的推理 - 這似乎是非常糟糕的做法,並沒有使任何「更簡單」。 – 2014-11-06 22:58:11

+1

這不是Objective-C代碼;請不要再添加該標籤。 – 2014-11-06 23:04:30

回答

1

記住你要保持大寫字母大寫的,所以當你轉移「Z」發生了什麼?

看看modulo運營商%來幫忙。

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

這是一些大寫字母的情況下的代碼,並會導致字母環繞。 'Z'+ 3變成'C'等。

+0

我在想類似的東西(雖然你的msgIn和out似乎不在),更像這樣: msgOut =((msgIn - 'A')+ shift)%26 +'A'; – loserspearl 2014-11-06 23:11:24

+0

@loserspearl感謝您的糾正。 – ryanpattison 2014-11-06 23:18:17

0

我猜你簡單,你的意思是容易理解你的兒子?您可以使用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;  
+0

你發現[魔術數字](http://en.wikipedia.org/wiki/Magic_number_(編程))更容易理解? – ryanpattison 2014-11-06 23:21:14

+0

什麼孩子不知道ASCII字符 - 只是在開玩笑。是的,字符更好。 – Nickel 2014-11-06 23:46:38