How do i increment letters in c++?

后端 未结 8 1325
渐次进展
渐次进展 2021-01-05 05:30

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 t

8条回答
  •  青春惊慌失措
    2021-01-05 05:46

    waleed@waleed-P17SM-A:~$ nano Good_morning_encryption.cpp waleed@waleed-P17SM-A:~$ g++ Good_morning_encryption.cpp -o Good_morning_encryption.out waleed@waleed-P17SM-A:~$ ./Good_morning_encryption.out Enter your text:waleed Encrypted text: jnyrrq waleed@waleed-P17SM-A:~$ cat Good_morning_encryption.cpp

        #include 
        #include 
    
        using namespace std;
    
    
        int main() {
    
        //the string that holds the user input
        string text;
        //x for the first counter than makes it keeps looping until it encrypts the user input
        //len holds the value (int) of the length of the user input ( including spaces)
        int x, len;
    
        //simple console output
        cout << "Enter your text:";
        //gets the user input ( including spaces and saves it to the variable text
        getline(cin, text);
        //give the variable len the value of the user input length
        len = (int)text.length();
        //counter that makes it keep looping until it "encrypts" all of the user input (that's why it keeps looping while its less than len
        for(x = 0; x < len; x++) {
        //checks each letts (and spaces) in the user input (x is the number of the offset keep in mind that it starts from 0 and for example text[x] if the user input was waleed would be w since its text[0]
        if (isalpha(text[x])) {
        //converts each letter to small letter ( even though it can be done another way by making the check like this if (text[x] =='z' || text[x] == 'Z')
        text[x] = tolower(text[x]);
        //another counter that loops 13 times
        for (int counter = 0; counter < 13; counter++) {
    
        //it checks if the letts text[x] is z and if it is it will make it a
        if (text[x] == 'z') {
    
        text[x] = 'a';
    
        } 
        //if its not z it will keeps increamenting (using the loop 13 times)
        else {
    
    
        text[x]++;
    
        }
    
        }
        }
        }
    //prints out the final value of text
        cout << "Encrypted text:\n" << text << endl;
        //return 0 (because the the main function is an int so it must return an integer value
        return 0;
    
        }
    

    Note: this is called caeser cipher encryption it works like this :

    ABCDEFGHIJKLMNOPQRSTUVWXYZ NOPQRSTUVWXYZABCDEFGHIJKLM so for example my name is waleed it will be written as : JNYRRQ so its simply add 13 letters to each letter

    i hope that helped you

提交回复
热议问题