Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I increment letters in c++?

I'm creating a Caesar Cipher in c++ and i can't figure out how to increment a letter.

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;
like image 443
Marobri Avatar asked Dec 13 '11 10:12

Marobri


People also ask

What happens when you increment a char in C?

This situation is known as overflow of signed char. Range of unsigned char is -128 to 127 . If we will assign a value greater than 127 then value of variable will be changed to a value if we will move clockwise direction as shown in the figure according to number.

What happens when you increment a char?

For example, incrementing a char pointer will increase its value by one because the very next valid char address is one byte from the current location. Incrementing an int pointer will increase its value by four because the next valid integer address is four bytes from the current location.

Can you increment a char in CPP?

7.10 Increment and decrement operators Incrementing and decrementing are such common operations that C++ provides special operators for them. The ++ operator adds one to the current value of an int, char or double, and -- subtracts one.


1 Answers

This snippet should get you started. letter is a char and not an array of chars 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!

like image 116
Johnsyweb Avatar answered Nov 15 '22 13:11

Johnsyweb