如何在 C++ 中增加字母?
我正在用 c++ 创建一个凯撒密码,但我不知道如何增加一个字母.
I'm creating a Caesar Cipher in c++ and i can't figure out how to increment a letter.
我需要每次将字母加 1 并返回字母表中的下一个字母.像下面这样将 1 添加到 'a' 并返回 'b'.
I need to increment the letter by 1 each time and return the next letter in the alphabet. Something like the following to add 1 to 'a' and return 'b'.
char letter[] = "a";
cout << letter[0] +1;
推荐答案
这个片段应该让你开始.letter 是 char 而不是 char 的数组也不是字符串.
This snippet should get you started. letter is a char and not an array of chars nor a string.
static_cast 确保 'a' + 1 的结果被视为 char.
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
当你到达 'z'(或 'Z'!)时要小心,祝你好运!
Watch out when you get to 'z' (or 'Z'!) and good luck!
相关文章