Char - Adding ABCs (letters)?...

I'm wondering how I can go back to an alphabet letter I want that letter to land on?

Adding capital letters. Lower case letters not needed.


For example;
- User enters "XYZ"
- Program comes up with the next 10 letters which would be something like 'HIJ' (Since X+10 = H, Y+10 = I, Z+10=J)

My problem is with the last few letters. The program goes to the next 10 characters ahead of those characters rather then the alphabet.

Program example: (What I want shown)
"What are your three favorite letters?" XYZ
"The next ten letters are: HIJ"


Error example: {It goes to the next 10 characters instead of the next 10 alphabet letters.)
"What are your three favorite letters?" XYZ
"The next ten letters are: ^[a"


Code example: (I've tried other ways as well.)
1
2
3
4
char a, b, c;
cout << "What are your three favorite letters?";
cin >> a >> b >> c;
cout << "The next ten letters are: " << a+10 << b+10 << c+10 << endl;
Last edited on
> My problem is with the last few letters. The program goes to the next 10 characters ahead of those

Modular arithmetic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <cctype>

int main()
{
    // http://www.mochima.com/tutorials/strings.html
    // since there is no guarantee that 'a' + 1 == 'b' 
    const std::string alphabet = "abcdefghijklmnopqrstuvwxyz";

    char favourites[3];
    std::cout << "What are your three favourite letters? ";

    // http://www.stroustrup.com/C++11FAQ.html#for
    for( char& letter : favourites ) std::cin >> letter ;
    
    std::cout << "\nletters 10 places away are: " ;
    for( char letter : favourites )
    {
        //http://www.cplusplus.com/reference/cctype/tolower/
        letter = std::tolower(letter) ;

        // http://www.cplusplus.com/reference/string/string/find/
        // http://www.stroustrup.com/C++11FAQ.html#auto
        auto pos = alphabet.find(letter) ;

        if( pos != std::string::npos )
            std::cout << alphabet[ (pos+10) % alphabet.size() ] ;
            // http://arduino.cc/en/Reference/Modulo

        else std::cout << '?' ;
    }
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/4abb3b36c7f6bb81
Thanks!

Is there a more basic way of doing it? Using just math or w/e.
Last edited on
You can examine to see if your addition has pushed the character passed 'Z'. And if it did, you can wrap back to the start by subtracting 26 (26 chars in the alphabet)

1
2
3
4
char foo = 'Y' + 10; // example input

if( foo > 'Z' ) // is it passed 'Z'?
    foo -= 26;  // yes?  Then subtract 26 to make it wrap. 

Ah. Thanks!
Topic archived. No new replies allowed.