cpp


C++ Source code to encrypt and decrypt the Ceasar cipher

The following code accepts one line from the standard input and uses the functions encrypt and decrypt to break the Ceasar cipher when the key is known. In this example, the key was the number 12, the day of birth of Julius Ceasar.

[download id=”11738″]

#include <iostream>
#include <string> 

using namespace std;

#define OFFSET_SMALL (97)
#define OFFSET_BIG (65)
#define LATIN_CHARACTERS (26)

// Text and offset for the shift are sent into this function, which returns the text's encrypted version.
string encrypt(string text, int offset)
{
    string result = "";

    for (long unsigned int i = 0; i < text.length(); i++)
    {
        if (std::isalpha(text[i]))
        {
            if (std::islower(text[i]))
            {
                result += char (int(text[i] + offset - OFFSET_SMALL) % LATIN_CHARACTERS + OFFSET_SMALL);
            }
            else
            {
                result += char (int(text[i] + offset - OFFSET_BIG) % LATIN_CHARACTERS + OFFSET_BIG);
            }
        }

        else
        {
            result += text[i];
        }
    }

    return result;
}

// Text and offset for the shift are sent into this function, which returns the text's decrypted version.
string decrypt(string text, int offset)
{
    return encrypt(text, LATIN_CHARACTERS - offset);
}

int main() {
    string encrypted;
    getline(cin, encrypted);

    // Sample execution showing how to decrypt an already encrypted message.
    // Julius Ceasar was born on July 12, 100BC
    cout << decrypt(encrypted, 12);

    return 0;
}

[download id=”11738″]

.

Side note:

While authoring this post, we found a peculiar bug in the plugin named “SyntaxHlighlighter Evolved.”

Specifically, when we added the string char( in our C++ source code, we would get the following error back:

Updating failed. The response is not a valid JSON response.

To mitigate the problem, we added a space character between the word char and the open parenthesis as follows char (.


Debugging Trick Using Variadic Macros in C and C++

Following you can find a very practical trick that allows you to enable/disable all prints to the screen with as little effort as possible while not dramatically increasing the overall code size to do this.

For C:  Place on the top of your code or on a header file the following:

#define ENABLE_DEBUG

#ifdef ENABLE_DEBUG
    #define XDEBUG(...) printf(__VA_ARGS__)
#else
    #define XDEBUG(...)  /**/
#endif

and then inside the code whenever you want to print some debug information do as follows:

XDEBUG("Max Weight %d, Total Trips %d\n", minMax, trips);

For C++:  Place on the top of your code or on a header file the following:

#define ENABLE_DEBUG

#ifdef ENABLE_DEBUG
    #define XDEBUG cout
#else
    #define XDEBUG if(0) cerr
#endif

and then inside the code whenever you want to print some debug information do as follows:

XDEBUG << "We got " << disks << " disks\n";