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

密码替换函数异常排查:输入abcd未得到预期密文yukf

问题排查与修复方案

核心问题:printf错误传递std::string对象

你的代码中所有printf调用都直接将std::string对象传递给%s格式符,这是未定义行为。printf的%s需要接收以\0结尾的C风格字符串(char*),而std::string是C++类对象,直接传递会导致printf读取错误的内存区域,从而输出错误结果(比如你看到的qidc)。

其他次要问题

  • 用strlen获取std::string长度:strlen需要遍历字符串直到\0,而std::string::size()是O(1)的高效操作,更适合获取长度。
  • 内层循环未及时终止:找到匹配的字母位置后,继续遍历剩余字母表字符会浪费性能,应立即跳出内层循环。
  • 字符处理的类型安全:tolower/isupper等函数的参数应为unsigned char,避免有符号char导致的未定义行为。

修复后的代码

#include <iostream>
#include <string>
#include <cctype>

// 接收密码表、用户输入、字母表,输出替换后的密文
void cipher_text(const std::string& cipher, const std::string& user_input, const std::string& alphabet)
{
    std::string result = user_input;
    const size_t alphabet_len = alphabet.size();
    const size_t input_len = user_input.size();

    for (size_t i = 0; i < input_len; ++i)
    {
        const char lower_input = std::tolower(static_cast<unsigned char>(user_input[i]));
        for (size_t k = 0; k < alphabet_len; ++k)
        {
            if (lower_input == alphabet[k])
            {
                if (std::islower(static_cast<unsigned char>(user_input[i])))
                {
                    result[i] = std::tolower(static_cast<unsigned char>(cipher[k]));
                }
                else
                {
                    result[i] = std::toupper(static_cast<unsigned char>(cipher[k]));
                }
                // 找到匹配后立即终止内层循环
                break;
            }
        }
    }
    // 使用c_str()获取C风格字符串传递给printf
    printf("ciphertext:  %s\n", result.c_str());
    // 或使用C++的cout更安全:
    // std::cout << "ciphertext:  " << result << std::endl;
}

验证效果

当传入cipher = "YUKFRNLBAVMWZTEOGXHCIPJSQD"、userinput = "abcd"、alphabet = "abcdefghijklmnopqrstuvwxyz"时,修复后的函数会正确输出yukf。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:10:24