C 的密码学错误

标签 c string cryptography

我正在尝试创建一个可以根据用户 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/

相关文章:

我可以将结构保存在文件中,例如 txt.file 吗?

c++ - 如何使用指针到指针来传递矩阵?

python - 变量的大小写折叠变化,因此输入与分配的变量之一匹配

c# - 如何明智地使用 StringBuilder?

javascript - Forge:加密大文件

flutter - 即使使用异步,在 Flutter 中进行繁重的计算操作时 UI 也会滞后

c - 读入文件以创建多个 "minesweeper"ish 数组

c - If-Else 语句不打印结果

java - 如何使用另一个字符串中的字符替换字符串中的字符(Caesar Cypher)(JAVA)

ssl - 如果 SSL/TLS 证书没有真正的签名/CA,为什么它们是自签名的?