凯撒密码 字符串移动问题

img

img


已经用了gets输入,为什么最后输出的时候仍然无法读取空格后面的字符呢

望采纳。以下是使用 C 语言实现凯撒密码的代码示例:

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

int main() {
    char plaintext[81]; // 存储明文
    int offset; // 偏移量

    // 读入明文
    fgets(plaintext, 81, stdin);
    // 去掉回车符
    plaintext[strlen(plaintext) - 1] = '\0';

    // 读入偏移量
    scanf("%d", &offset);

    // 如果偏移量不在有效范围内,则输出 Invalid
    if (offset < 0 || offset > 25) {
        printf("Invalid.");
        return 0;
    }

    // 加密
    for (int i = 0; i < strlen(plaintext); i++) {
        char ch = plaintext[i];

        // 如果是小写字母
        if (islower(ch)) {
            // 转换为大写字母
            ch = (char) (ch - 'a' + 'A');
        }

        // 如果是大写字母
        if (isupper(ch)) {
            // 加密
            ch = (char) ((ch - 'A' + offset) % 26 + 'A');
        }

        // 输出密文
        printf("%c", ch);
    }

    return 0;
}

可以参考ASCII码