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++ 中增加字母?
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
