我正在尝试创建一个可以根据用户 key 修改文本的程序。它似乎运行良好,直到我输入一些东西并且它添加了额外的东西。
例如,如果我添加单词 hello 和键 3,它表示 khoor 加上一些额外的奇怪字符。你能告诉我有什么问题吗?非常感谢。
#include <stdio.h>
#include <ctype.h>
#define MAXSIZE 100
void encrypt(senTence[], int key);
int main(void)
{
int userKey;
char sentence[MAXSIZE];
printf("Input the text that you want to encrypt:\n> ");
fgets(sentence, 99, stdin);
// printf("\nThe string that you wrote is:\n%s\n\n", sentence);
printf("Input the key:\n");
scanf("%d", &userKey);
//printf("\nThe key that you selected is: %d\n\n", userKey);
encrypt(sentence, userKey);
return 0;
}
void encrypt(const char senTence[], int key)
{
int i = 0;
char q[MAXSIZE];
for(i = 0; senTence[i] != '\0'; ++i)
{
if( ( isupper(senTence[i]) ) || ( islower(senTence[i]) ) )
{
q[i] = senTence[i] + (char)key;
}
else
{
q[i] = (senTence[i]);
}
}
printf("%s", q);
}
最佳答案
您没有在 encrypt()
中终止结果字符串 q
。
在 printf()
之前添加以下行。
q[i] = '\0';
另一种方法是将q
初始化为全零:
char q[MAXSIZE] = {0};
关于C 的密码学错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27417295/