簡體   English   中英

凱撒密碼和反向文本程序

[英]Caesar cipher and reverse text program

我正在嘗試制作一個獲取字符串和數字的函數,如果數字較大,則為“ 0”,這樣它將使凱撒密碼與字符串和用戶輸入的數字一致。 例如->'stack',數字是'3'->'uvdfn'。 如果數字為“ 0”,則它將反轉字符串。 例如-'stack'->'kcats'

我不知道代碼有什么問題,我看不到任何錯誤。

 /********************************* * Class: MAGSHIMIM C2 * * Week 3 * ********************************** * Thank you for Ofek and Dor for * * Editing this template :) * **********************************/ #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); } } 

反轉字符串時,您是從前到后交換字母,然后是從后到前交換字母,因此最終得到的是與開頭相同的字符串。 您也不需要使用所有指針,因為您可以使用數組下標,這樣可以提高可讀性。 嘗試更多類似這樣的方法:

j = strLen-1;
for (i = 0; i < strLen/2; i++, j--) {
    temp = encText[i];
    encText[i] = encText[j];
    encText[j] = temp;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM