【发布时间】:2017-11-08 18:47:52
【问题描述】:
我正在用 C 语言创建凯撒密码,但在显示编码消息时遇到了问题。如果消息由很少的字符组成,但只要消息超过一定数量的字符,printf 函数就会开始显示我认为是垃圾字节的未知字符。有什么想法吗?
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *concat(const char *s1, const char *s2)
{
/*
Remember to free allocated memory
*/
char *result;
if((result = malloc(strlen(s1)+strlen(s2)+1)) != NULL)
{
result[0] = '\0';
strcat(result, s1);
strcat(result, s2);
}
return result;
}
void encode(const char *alpha, const char *message)
{
char result[(sizeof(message) / sizeof(char))];
int x, y, z;
memset(result, '\0', sizeof(result));
for(x = 0; x < strlen(message); x++)
{
for(y = 0; y < 25; y++)
{
if(alpha[y] == message[x])
{
z = (y + 3);
if(z > 25)
{
z = z % 25;
}
result[x] = alpha[z];
}
}
}
printf("%s\n", result);
//return result;
}
int main()
{
char message[200];
char *result;
char array[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
printf("Input your message:");
scanf("%s", &message);
encode(array, message);
}
结果:
【问题讨论】:
-
scanf("%s", &message);是错误的。应该是scanf("%s", message); -
刚刚更正了,谢谢。我对 C 很陌生
-
尽量不要在循环中调用strlen for(x = 0; x
标签: c caesar-cipher