1

我正计划创建一个加密程序。基本上将正常的“abcdefghijklmnopqrstuvwxyz”中的任何内容交换为“thequickbrownfxjmpsvlazydg”。

例如,如果我要键入“abc”,结果将是“the”。

#include <stdio.h>
#include <string.h>

void encrypt(char *text, char *map);
void decrypt(char *text, char *map);

int main()
{

    char a[] = {'a','b','c','d','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    char b[] = {'t','h','e','q','u','i','c','k','b','r','o','w','n','f','x','j','m','p','s','v','l','a','z','y','d','g'};
    char *textptr;
    char *mapptr;

    textptr = a;
    mapptr = b;

    encrypt(textptr, mapptr);

    return 0;
}

void encrypt(char *text, char *map)
{
    char string[100];
    int len;
    int x = 0, y = 0, l = 1;

    printf("Please enter the string: ");
    scanf("%s", string);
    len = strlen(string);

    for (x = 0; x < len; x++)
    {
    for (y = 0; y < 26; y++)
    {
    if(text[x] == map[y])
    text[x] = map[y];
    }
    }

    printf("The Ciphertext is: %s", string);
}

并且输出与输入的纯文本相同..你们能帮我吗?

4

3 回答 3

1

这就是问题:

 if(text[x] == map[y])
   text[x] = map[y];

利用:

 if(string[x] == text[y])
   string[x] = map[y];
于 2013-09-02T09:41:52.197 回答
1

你的问题出在这里:

strcpy (string[q],map[r]);

您将两个chars 传递给strcpy()而不是char *. 要替换单个字符,只需执行

string[q] = map[r];

编辑:新代码

if(text[x] == map[y])
   text[x] = map[y];

这显然没有任何改变。它应该是

if( string[x] == text[y] )
   string[x] = map[y];
于 2013-09-02T09:36:48.623 回答
0

您可以通过简单地使用单个 for 循环来做到这一点。并且您需要定义数组 a[]。

for (x = 0; x < strlen(string); x++)
{
string[x]=map[string[x]-'a'];

}    

修改后的代码:

#include <stdio.h>
#include <string.h>
#include<ctype.h>
void encrypt(char *map);

int main()
{

    char b[] = {'t','h','e','q','u','i','c','k','b','r','o','w','n','f','x','j','m','p','s','v','l','a','z','y','d','g'};
    char *mapptr;
    mapptr = b;
    encrypt(mapptr);
    return 0;
}

void encrypt(char *map)
{
    char string[100];
    int x = 0;

    printf("Please enter the string: ");
    scanf("%s", string);

    for (x = 0; x < strlen(string); x++)
    {
    if(islower(string[x]))
    string[x]=map[string[x]-'a'];

    }

    printf("The Ciphertext is: %s\n", string);
}
于 2013-09-02T09:44:49.370 回答