简体   繁体   English

凯撒密码和逆向文本程序的问题

[英]Issue with caesar cipher and reverse text program

I'm trying to make a function that gets a string and a number and if the number is bigger the '0' so it will make the caesar cipher with the string and the number that the user entered.我正在尝试制作一个获取字符串和数字的函数,如果数字大于“0”,那么它将使用字符串和用户输入的数字制作凯撒密码。 for example -> 'stack' and the number is '3' -> 'uvdfn'.例如 -> 'stack' 并且数字是 '3' -> 'uvdfn'。 if the number is '0' so it will reverse the string.如果数字是“0”,那么它将反转字符串。 for example - 'stack' -> 'kcats'例如 - 'stack' -> 'kcats'

I don't know what is the issue with the code, i don't see anything wrong.我不知道代码有什么问题,我没有看到任何错误。

 #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;
    }

Should be应该

if (*(encText + i) + n > 'z')
{
    *(encText + i) = (*(encText + i)) - 26;
}

The error in your encoding part is the following snippet:您的编码部分中的错误是以下代码段:

if (*(encText + i) >= 'x')
{
    *(encText + i) = (*(encText + i)) - 26;
}
*(encText + i) = (*(encText + i)) + n;

First of all you have to determine if you get lower- or uppercase input.首先,您必须确定是小写还是大写输入。 For beginning we assume lowercase input only.一开始,我们假设只输入小写字母。 In this snippet you firstly have to subtract an 'a' from the actual character, secondly add the chosen rotation number to the calculated value, thirdly calculate the modul of that and fourthly add an 'a' to the value.在此代码段中,您首先必须从实际字符中减去一个“a”,其次将选定的旋转数添加到计算值中,第三次计算其模数,第四次将“a”添加到值中。

char temp;
temp = *(encText + i);
temp -= 'a';
temp += n;
temp %= 26;
temp += 'a';
*(encText + i) = temp;

or in short:或简而言之:

*(encText + i) = (*(encText + i) - 'a' + n) % 26 + 'a';

BTW: Your cracking operation doesnt look very effective...顺便说一句:你的破解操作看起来不是很有效......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM