【问题标题】:Caesar cipher and reverse text program凯撒密码和反向文本程序
【发布时间】:2016-03-26 00:04:34
【问题描述】:

我正在尝试创建一个获取字符串和数字的函数,如果数字更大,则为“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);
	}
}

【问题讨论】:

    标签: c string pointers caesar-cipher


    【解决方案1】:

    当反转字符串时,您是从前到后交换字母,然后从后到前交换,因此您最终会得到与开始时相同的字符串。您也不需要使用所有指针,因为您可以使用数组下标,使其更具可读性。尝试更多类似的方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 1970-01-01
      相关资源
      最近更新 更多