【问题标题】:Shifting characters in C++C++中的字符转换
【发布时间】:2013-09-14 09:39:00
【问题描述】:

我尝试编写一个函数来进行简单的字符移动(向左或向右,取决于以下函数中的 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' 及以上时,此功能将停止正常工作。谁能指出我的方法有什么问题?

提前致谢。

【问题讨论】:

  • 你为测试提供的shift的值是多少?
  • int('z') - 1 不需要从字符文字到整数类型的转换,因为char 是整数类型(不是int,而是整数)。
  • 至少对于某些价值观来说,它就像魅力一样。可以提供调用代码吗?
  • Re timrau,我使用了值 13 作为 shift 参数。
  • 使用unsigned char 代替字符

标签: c++ character


【解决方案1】:

's' + 13 将溢出签名的char。将结果保存在int 中,并在调整数字后返回之前转换为char

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2013-01-27
    • 2014-05-02
    • 2020-02-20
    • 2015-07-08
    • 1970-01-01
    相关资源
    最近更新 更多