How do I increment letters in c++?(如何在 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!
这篇关于如何在 C++ 中增加字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C++ 中增加字母?
基础教程推荐
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
