【问题标题】:Issue with caesar cipher and reverse text program凯撒密码和反向文本程序的问题
【发布时间】:2016-03-26 09:13:07
【问题描述】:

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

【问题讨论】:

  • “我不知道代码有什么问题”——好吧,我们也不知道。你为什么不花几分钟来解释一下到底是什么问题? (即,你用什么输入测试过它,你得到了什么不正确的输出,当你一步一步调试你的代码时你的观察结果等等)。
  • for (j = 0; j &gt;= 0; j--) 不会做任何事情。
  • 嘿巴拉克,对不起...问题是在凯撒密码的情况下,什么都没有发生,它不会打印它的结果。在反向文本的情况下,它打印用户输入的相同字符串。 @barakmanos
  • 当您逐步调试代码时,您的观察结果是什么?
  • 黑猫跑出了门。神秘的 meg 电话已脱机。请告知下一个行动方案

标签: c string pointers


【解决方案1】:
if (*(encText + i) >= 'x')
    {
        *(encText + i) = (*(encText + i)) - 26;
    }

应该是

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

【讨论】:

  • 谢谢,但出于某种原因,如果我输入 'wxyz' 作为字符串,输入 '4' 作为数字,它会打印 '{|}~'
【解决方案2】:

您的编码部分的错误是以下sn-p:

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

首先,您必须确定输入的是小写字母还是大写字母。首先,我们假设只输入小写字母。 在这个 sn-p 中,您首先必须从实际字符中减去一个“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';

顺便说一句:你的破解操作看起来不太有效......

【讨论】:

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