2013-11-26 36 views
-1
#include <stdio.h> 

void caesar(char bemenet[], char eredmeny[], int n){ 
int i = 0; 
    for(i = 0; bemenet[i] != '\0'; i++) { 
     if(bemenet[i] == 'z') { 
      eredmeny[i] = 'a'; 
      eredmeny[i] += n-1; 
     } 
     else 
     { 
      eredmeny[i] += n; 
     } 
    } 
    eredmeny[i] = '\0'; 
} 

int main(){ 
char tomb1[]="caesarkodolas"; 
char tomb2[]=""; 

caesar(tomb1,tomb2,1); 

printf("%s \n",tomb2); 

return 0; 
} 

我對「eredmeny」(結果)這一點: 「dbftbslpepmb」但tomb2 =>☺dbftbslpepmb這也不行..因爲我有一個額外的字符|☺| ..凱撒代碼在結果C額外信

+0

輸出數組太小,所以這是明顯的未定義的行爲。 –

+0

這種方法已被破壞 - 它不適用於'1'上方的'n'。嘗試使用'caesar(tomb1,tomb2,10);'[查看一些垃圾輸出](http://ideone.com/cyVmK0)「修改後的代碼。 – dasblinkenlight

回答

0

首先你應該有足夠大的tomb2來存儲結果。

例如,上述

char tomb2[255] = {0}; 

也提到你有錯誤這裏

else 
{ 
    eredmeny[i] += n; 
} 

你必須有效的ASCII值分配給eredmeny[i]所以這個字符串變成

eredmeny[i] += bemenet[i] + n

另外它通常不好的做法是傳遞數組上的指針而不傳遞其大小。容易得到緩衝區溢出。

+0

謝謝你現在的工作! – 18uploadz

+0

既然你接受了這個答案,請看看@dasblinkenlight的建議如何寫出算法的防彈版本。 – Deck

1

分配足夠的內存爲第二個參數,並更改該行

eredmeny[i] += n; 

這樣:

eredmeny[i] = bemenet[i] + n; 

注意,這是不是防彈實施Caesar cipher:其將工作n==1,但它會打破更大的n

你需要考慮的實現「環繞」的方式不同:而不是測試爲'z''a'替換它,計算了一封信模26的新位置,然後添加a它:

void caesar(char bemenet[], char eredmeny[], int n){ 
    int i; 
    for(i = 0; bemenet[i] != '\0'; i++) { 
     // Compute the position of the replacement letter 
     int pos = (bemenet[i] - 'a' + n) % 26; 
     // Place the letter into the output. 
     eredmeny[i] = 'a' + pos; 
    } 
    eredmeny[i] = '\0'; 
} 

demo.

0

你沒有做數學的權利。

如果你使用的只是小寫字母,那麼你需要添加n,但是接下來很多字母會在z之後,所以你需要重新開始。

你想要更多的東西是這樣的:

for(i = 0; bemenet[i] != '\0'; i++) { 
    int encrypted = bemenet[i] + n; 
    if (encrypted > 'z') encrypted = encrypted - 'z' + 'a'; 
    eredmeny[i] = (char)encrypted; 
} 

(這裏在其他的答案中描述並修復了輸出數組的大小)。