How do I increment letters in c++?
It works as-is, but because the addition promotes the expression to int
you want to cast it back to char
again so that your IOStream renders it as a character rather than a number:
int main() {
char letter[] = "a";
cout << static_cast<char>(letter[0] + 1);
}
Output: b
Also add wrap-around logic (so that when letter[0]
is z
, you set to a
rather than incrementing), and consider case.
This snippet should get you started. letter
is a char
and not an array of char
s nor a string.
The static_cast
ensures the result of 'a' + 1
is treated as a char
.
> cat caesar.cpp
#include <iostream>
int main()
{
char letter = 'a';
std::cout << static_cast<char>(letter + 1) << std::endl;
}
> g++ caesar.cpp -o caesar
> ./caesar
b
Watch out when you get to 'z'
(or 'Z'
!) and good luck!