[英]Issue with caesar cipher and reverse text program
我正在嘗試制作一個獲取字符串和數字的函數,如果數字大於“0”,那么它將使用字符串和用戶輸入的數字制作凱撒密碼。 例如 -> 'stack' 並且數字是 '3' -> 'uvdfn'。 如果數字是“0”,那么它將反轉字符串。 例如 - 'stack' -> 'kcats'
我不知道代碼有什么問題,我沒有看到任何錯誤。
#include <stdio.h> #include <stdlib.h> #include <string.h> void decryptText(char* encText, int n); #define STR_SIZE 50 int main(void) { char str[STR_SIZE]; int num = 0; printf("Please enter the string : "); fgets(str, STR_SIZE, stdin); printf("Please enter a number : "); scanf("%d", &num); decryptText(str, num); system("PAUSE"); return 0; } void decryptText(char* encText, int n) { int i = 0; int j = 0; char temp = 0; int strLen = strlen(encText); if (n > 0) { for (i = 0; i < strLen; i++) { if (*(encText + i) == ' ') { } else { if (*(encText + i) >= 'x') { *(encText + i) = (*(encText + i)) - 26; } *(encText + i) = (*(encText + i)) + n; } } printf("The array after the program deciphered it : \\n"); printf("%s", encText); } else if (n == 0) { for (i = 0; i < strLen; i++) { for (j = 0; j >= 0; j--) { temp = *(encText + i); *(encText + i) = *(encText + j); *(encText + i) = temp; } } printf("The array after the program cracked it : \\n"); printf("%s", encText); } }
if (*(encText + i) >= 'x')
{
*(encText + i) = (*(encText + i)) - 26;
}
應該
if (*(encText + i) + n > 'z')
{
*(encText + i) = (*(encText + i)) - 26;
}
您的編碼部分中的錯誤是以下代碼段:
if (*(encText + i) >= 'x')
{
*(encText + i) = (*(encText + i)) - 26;
}
*(encText + i) = (*(encText + i)) + n;
首先,您必須確定是小寫還是大寫輸入。 一開始,我們假設只輸入小寫字母。 在此代碼段中,您首先必須從實際字符中減去一個“a”,其次將選定的旋轉數添加到計算值中,第三次計算其模數,第四次將“a”添加到值中。
char temp;
temp = *(encText + i);
temp -= 'a';
temp += n;
temp %= 26;
temp += 'a';
*(encText + i) = temp;
或簡而言之:
*(encText + i) = (*(encText + i) - 'a' + n) % 26 + 'a';
順便說一句:你的破解操作看起來不是很有效......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.