简体   繁体   中英

Shifting characters in C++

I tried to write a function to do simple shifting of characters (either to the left or right, depending on the shift parameter in the following function). Capital letters remain to be capital letters. Here is my approach:

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;
}

This function stops working properly when the input character is 's' and beyond. Could anyone please point out what's the problem to my approach?

Thanks in advance.

's' + 13 will overflow a signed char . Keep the result in an int and cast to char after adjusting the number and before returning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM