[英]Caesar Cipher Program to Encrypt/Decrypt a paragraph
首先,我是編程新手,所以要保持柔和。 另外,我一直在從事這項工作,但沒有成功。 任務是創建一個Caesar Cipher程序,該程序可以加密或解密最多100個字符的段落。 實際上是兩個單獨的實驗室。 第一個實驗是加密,然后第二個實驗是解密。 一旦弄清如何創建加密程序,解密程序就應該很簡單,因為我可以進行語義更改以解密而不是加密。 無論如何,這里是我到目前為止的代碼。 它通過了我們給我們的5個測試中的4個,但是由於某種原因,有一個測試的最終字符是一個'@'符號。 這對我來說沒有意義,因為它不會在其他任何測試中發生,並且我認為我的代碼在字符串的處放置了“ \\ 0”符號,因此在此測試中不應顯示“ @”。
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
// ---------------------- DO NOT MODIFY THIS SECTION ----------------------- ---------
#define MAX_PGRAPH_LENGTH 100
#define MAX_WORD_LENGHT 20
int main(void) {
// definitions
char plaintext[MAX_PGRAPH_LENGTH] = "";
char ciphertext[MAX_PGRAPH_LENGTH];
char input[MAX_WORD_LENGHT];
// read the key
int key;
scanf("Key: %d, ", &key);
// read text
scanf("Input: ");
while (true)
{
scanf("%s", input);
if (strlen(plaintext) + strlen(input) + 1 > MAX_PGRAPH_LENGTH)
break;
strcat(plaintext, input);
strcat(plaintext, " ");
}
plaintext[strlen(plaintext) - 1] = '\0';
// ---------------------- -------------------------------------------------- ---------
int i;
for(i = 0; i < strlen(plaintext); ++i)
{
if(plaintext[i] >= 'a' && plaintext[i] <= 'z') {
ciphertext[i] = ((plaintext[i] + (key % 26) - 97) % 26) + 97;
if(ciphertext[i] > 'z') {
ciphertext[i] = ((plaintext[i] + (key % 26) - 97) % 26) + 97 - 26; }
}
else if(plaintext[i] >= 'A' && plaintext[i] <= 'Z') {
ciphertext[i] = ((plaintext[i] + (key % 26) - 'A') % 26) + 'A';
if(ciphertext[i] > 'Z') {
ciphertext[i] = ((plaintext[i] + (key % 26) - 'A') % 26) + 'A' - 26; }
}
else {
ciphertext[i] = plaintext[i]; }
}
for(i = 0; i < strlen(plaintext) && plaintext[i] == '\0'; ++i) {
ciphertext[i] = '\0'; }
// ---------------------- DO NOT MODIFY THIS SECTION ----------------------- ---------
printf(" Key: %d\n", key);
printf(" Input: %s\n", plaintext);
printf("Output: %s\n", ciphertext);
// ---------------------- -------------------------------------------------- ---------
}
如您所見,實驗室為我們提供了設置和多個代碼塊,我負責編碼的實際Caesar密碼部分。 我的問題是,我在C的最后位置是否未正確設置'\\ 0'? 我還注意到的一件事是,如果我輸入“狗跑了”之類的輸入,當輸入被打印到屏幕上時,它將打印“狗跑了ran跑了..”,直到達到100個字符。 幸運的是,它們提供給我們的所有測試都是超過100個字符的段落,因此我實際上不必擔心通過一個加密少於100個字符的測試。 但是我仍然想知道為什么我的明文字符串會不斷重復最后一個輸入的單詞。 抱歉,發布了這么長的帖子,我已盡力嘗試了一切,卻不知道我要去哪里出錯。
它重復最后一個單詞,因為您不會退出無限循環。
while (true)
{
scanf("%s", input);
if (strlen(plaintext) + strlen(input) + 1 > MAX_PGRAPH_LENGTH)
break;
strcat(plaintext, input);
strcat(plaintext, " ");
}
退出循環的唯一方法是執行break
語句,並且只有在input
和plaintext
總長度大於MAX_PGRAPH_LENGTH
,這才是可能的。 之所以只重復最后一個單詞,是因為scanf()
很可能逐字讀取輸入的單詞。
另外,未通過@字符通過測試用例的原因可能是由於字母字符以十進制65開頭(對應於A),而@的十進制值為64。A和@之間的區別是1和用@導致測試用例失敗的代碼在我看來不是巧合。 因此,我認為您應該仔細檢查算術運算並跟蹤示例輸入的代碼。
重復出現在提供的代碼中……不在您的代碼中。
永遠閱讀下一個單詞,直到達到最大段落長度。 如果沒有下一個單詞,則輸入的值不會更新,只會重復輸入,直到總長度達到MAX_PGRAPH_LENGTH
while (true)
{
scanf("%s", input);
if (strlen(plaintext) + strlen(input) + 1 > MAX_PGRAPH_LENGTH)
break;
strcat(plaintext, input);
strcat(plaintext, " ");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.