String Encryption with character rotation - C++ STL

C++ examples for STL:string

Description

String Encryption with character rotation

Demo Code

#include <iostream>
#include <string>

int getChoice();/*from w w w.java 2s.  com*/
const std::string rot13(const std::string&);

int main(int argc, const char* argv[]) {
    int choice = 0;

    std::string base = "test";
    std::cout << "ROT13 Encryption:\n" << rot13(base) << std::endl;

    base = "test";
    std::cout << "ROT13 decryption:\n" << rot13(base) << std::endl;
    return 0;
}
// encrypt/decrypt rot13 shift each character by 13 places (+/-)
const std::string rot13(const std::string& base) {
    std::string::const_iterator it = base.begin();
    std::string result = "";

    while (it != base.end()) {
        int ascii = *(it++);

        // first half upper/lower case
        if ((ascii >= 97 && ascii < 110) || (ascii >= 65 && ascii < 78))
            ascii = (ascii + 13);
        // second half
        else if ((ascii >= 110 && ascii <= 122) || (ascii >= 78 && ascii <= 90))
            ascii = (ascii - 13);

        result += ascii;
    }
    return result;
}

Result


Related Tutorials