我打算创建一个加密程序。基本上将任何来自正常“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);
}
并且输出与输入的纯文本相同..你能帮助我吗?
答案 0 :(得分:1)
你的问题在于:
strcpy (string[q],map[r]);
您已将两个char
传递给strcpy()
而不是char *
。要替换单个字符,只需执行
string[q] = map[r];
编辑:新代码
if(text[x] == map[y])
text[x] = map[y];
这显然没有改变。它应该是
if( string[x] == text[y] )
string[x] = map[y];
答案 1 :(得分:1)
这是问题所在:
if(text[x] == map[y])
text[x] = map[y];
使用:
if(string[x] == text[y])
string[x] = map[y];
答案 2 :(得分:0)
你可以通过简单的单循环来实现。你需要定义数组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);
}