Regarding your current code, personally I'm against ASCII code hackery such as adding the number 5 to a character (you can see this in the article as well).
You still need to do range checking before line 10 and repeat the same for capital letters. If you don't do range checking you might get into trouble with spaces, and other characters
While I can admire the wicked beauty of ats15's code, I strongly believe that it is hard to read and even harder to understand.
You can make the code more elegant if instead of ASCII arithmetic you use an alphabet string. If the character read is not in the string, write it back as is. Otherwise if the character read is in the string, simply shift by the required positions (looping if necessary).
Yes, but what about the letter Z? It's a letter, so I have to apply the number to it, which will push it out of the alphabet. Assuming I don't know my number beforehand, how would I go about looping back to A?
#include <iostream>
#include <string>
//
// Get character at `position' with regards to `current' character.
//
char get_next(char current, int position)
{
// construct out alphabet
const std::string alphabet("abcdefghijklmnopqrstuvwxyz");
// find where the `current' character is in the alphabet
const std::string::size_type current_position = alphabet.find(current);
if (current_position == std::string::npos)
throw"Couldn't find your character!"; // sloppy, but this is just an example
// get position of our target character
int target_position = static_cast<int> (current_position) + position;
// use modulo to make sure that `target_position' is within the alphabet's length
target_position %= static_cast<int> (alphabet.length());
// if `target_position' is negative, inverse it with regards to the alphabet's length
if (target_position < 0)
target_position += alphabet.length();
return alphabet.at(target_position);
}
int main()
{
std::cout << get_next('a', 1) << '\n';
std::cout << get_next('a', -1) << '\n';
std::cout << get_next('b', 3) << '\n';
std::cout << get_next('x', 3) << std::endl;
}