凯撒密码和反向文本程序

时间:2016-03-26 00:04:34

标签: c string pointers caesar-cipher

我试图创建一个获取字符串和数字的函数,如果数字更大,那么' 0'所以它会使用字符串和用户输入的数字来制作凯撒密码。 例如 - > '堆'这个数字是' 3' - > ' uvdfn&#39 ;. 如果数字是' 0' 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);
	}
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

当翻转字符串时,您正在从前向后交换字母,然后从后向前交换字母,因此您最终会得到与您开始时相同的字符串。您也不需要使用所有指针,因为您可以使用数组下标,这使它更具可读性。尝试更像这样的东西:

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