You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅用C++ string和循环实现凯撒密码移位加密功能

C++ 简易移位加密实现(仅用string和循环)

修正后可运行完整代码

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string plain_text;
    int shift_num;

    cout << "请输入待加密文本:";
    getline(cin, plain_text);

    cout << "请输入移位位数(正整数):";
    cin >> shift_num;
    // 移位位数对26取模,避免过大数值重复计算
    shift_num %= 26;

    // 循环遍历字符串每一位处理移位
    for (int i = 0; i < plain_text.size(); i++) {
        char current_char = plain_text[i];
        if (current_char >= 'a' && current_char <= 'z') {
            // 处理小写字母循环移位
            plain_text[i] = 'a' + (current_char - 'a' + shift_num) % 26;
        } else if (current_char >= 'A' && current_char <= 'Z') {
            // 处理大写字母循环移位
            plain_text[i] = 'A' + (current_char - 'A' + shift_num) % 26;
        }
        // 非字母字符(空格、标点等)不做修改直接保留
    }

    // 输出加密结果
    cout << plain_text << endl;

    system("PAUSE");
    return 0;
}

关键逻辑说明

  • 变量定义修正:拆分原代码错误的混合类型声明,移位位数定义为int类型
  • 整行输入适配:用getline(cin, plain_text)替代cin >>读取文本,支持输入带空格的完整句子,匹配示例运行效果
  • 移位核心逻辑:
    • 小写字母以a为基准计算偏移量,大写字母以A为基准计算偏移量,加移位值后模26实现循环移位,解决z移位后回到字母开头的需求
    • 非字母字符直接保留,不用做任何处理

内容的提问来源于stack exchange,提问作者PN911

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:27:02