在C++中移动角色

Shifting characters in C++

本文关键字:角色 移动 C++      更新时间:2023-10-16

我尝试编写一个函数来执行简单的字符移动(向左或向右移动,具体取决于以下函数中的 shift 参数)。大写字母仍然是大写字母。这是我的方法:

char encodeCaesarCipherChar(char ch, int shift)
{
    char result;
    if (!isalpha(ch)) return ch;
    result = ch + shift;
    if (islower(ch) && result < 'a') {
        result += int('z') - 1;
        result -= int('a');
    } else if (islower(ch) && result > 'z') {
        result -= int('z');
        result += int('a') - 1;
    }  else if (isupper(ch) && result < 'A') {
        result += int('Z') - 1;
        result -= int('A');
    }  else if (isupper(ch) && result > 'Z') {
        result -= int('Z');
        result += int('A') - 1;
    }
    return result;
}

当输入字符为"s"及以后时,此函数将停止正常工作。谁能指出我的方法有什么问题?

提前谢谢。

's' + 13 将溢出有符号char。将结果保留在int中,并在调整数字后和返回之前投射到char