c语言字符串加密的问题

字符串加密
【问题描述】Julius Caesar(凯撒)加密方法。该方法在每次加密时都选定一个加密密钥,它是一个1到25之间的数字,用于指定加密字母时的移位个数。例如,如果密钥为3,则将A转换为D,将Z转换为C,依次类推。小写字母亦如此(参见下图),其它字符不变。用该方法对一批加密。提示: % 26。

【要求】在main 函数调用 void encrpt(char* plaintext,char* ciphertext,int key) 完成编程。其中,plaintext表示明文,ciphertext表示密文。

【输入形式】

从标准输入中输入一个1到25之间的整数作为密钥key,然后从标准输入n行字符串,包含空格。每个字符串最长不超过80个字符。
【输出形式】

对输入内容按上述方法进行加密后输出。
【样例输入】

3 2

c 12.
WO AI BEIJING TIANANMEN.
【样例输出】加密

f 12.
ZR DL EHLMLQJ WLDQDQPHQ.
【样例说明】
根据输入密钥和转换公式对输入内容进行加密,并将结果输出。

请问这个怎么写呀,就是用不用函数都写得有问题

以下是一个C语言实现字符串加密的例子,其中包括了一个 encrypt 函数用于加密单个字符串,以及 main 函数用于读入输入并输出加密结果。具体实现过程中,我们需要注意字符串的处理方式,以及如何将字符按照要求进行移位加密。


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

void encrypt(char* plaintext, char* ciphertext, int key) {
    int i;
    char c;
    for (i = 0; plaintext[i] != '\0'; i++) {
        c = plaintext[i];
        if (isalpha(c)) {
            if (isupper(c)) {
                c = 'A' + (c - 'A' + key) % 26;
            } else {
                c = 'a' + (c - 'a' + key) % 26;
            }
        }
        ciphertext[i] = c;
    }
    ciphertext[i] = '\0';
}

int main() {
    int key;
    scanf("%d", &key);

    char plaintext[81], ciphertext[81];
    while (fgets(plaintext, 81, stdin) != NULL) {
        encrypt(plaintext, ciphertext, key);
        printf("%s", ciphertext);
    }

    return 0;
}

在这个例子中,我们首先定义了一个 encrypt 函数,用于加密单个字符串。在这个函数中,我们使用了一个循环来遍历输入的明文字符串中的每个字符。对于每个字符,我们首先判断它是否是字母,如果是,则按照要求进行移位加密。最后,我们将加密后的字符存入输出的密文字符串中。

在 main 函数中,我们首先读入密钥 key。然后,我们使用一个循环来逐行读入明文字符串,并调用 encrypt 函数进行加密。最后,我们将加密后的结果输出到标准输出中。

需要注意的是,我们在读入明文字符串时使用了 fgets 函数,而不是 scanf 函数。这是因为 fgets 函数可以读取包含空格的字符串,而 scanf 函数无法处理空格。

#include <stdio.h>
#include <string.h>
void encrpt(char* plaintext,char* ciphertext,int key) 
{
    int len = strlen(plaintext);
    for(int i=0;i<len;i++)
    {
        if(plaintext[i] >='A' && plaintext[i] <= 'Z')
            ciphertext[i] = (plaintext[i] - 'A' + key) % 26 + 'A';
        else if(plaintext[i] >='a' && plaintext[i] <= 'z')
            ciphertext[i] = (plaintext[i] - 'a' + key) % 26 + 'a';
        else
            ciphertext[i] = plaintext[i];
    }
    ciphertext[len] = 0;
}

int main()
{
    int key = 0,rep = 0;
    char in[81] = {0},out[81] = {0};
    scanf("%d%d",&key,&rep);
    getchar();
    for(int i=0;i<rep;i++)
    {
        gets(in);
        encrpt(in,out,key);
        printf("%s\n",out);
    }
    return 0;
}