can someone tell me how this program works? I'm trying to learning C++ by reading some examples, and this one is one of them.

#include <iostream>
#include <string>
using namespace std;
 
class Vigenere
{
public:
  string key;
 
  Vigenere(string key)
  {
    for(int i = 0; i < key.size(); ++i)
    {
      if(key[i] >= 'A' && key[i] <= 'Z')
        this->key += key[i];
      else if(key[i] >= 'a' && key[i] <= 'z')
        this->key += key[i] + 'A' - 'a';
    }
  }
 
  string encrypt(string text)
  {
    string out;
 
    for(int i = 0, j = 0; i < text.length(); ++i)
    {
      char c = text[i];
 
      if(c >= 'a' && c <= 'z')
        c += 'A' - 'a';
      else if(c < 'A' || c > 'Z')
        continue;
 
      out += (c + key[j] - 2*'A') % 26 + 'A'; 
      j = (j + 1) % key.length();
    }
 
    return out;
  }
 
  string decrypt(string text)
  {
    string out;
 
    for(int i = 0, j = 0; i < text.length(); ++i)
    {
      char c = text[i];
 
      if(c >= 'a' && c <= 'z')
        c += 'A' - 'a';
      else if(c < 'A' || c > 'Z')
        continue;
 
      out += (c - key[j] + 26) % 26 + 'A'; 
      j = (j + 1) % key.length();
    }
 
    return out;
  }
};
 
int main()
{
  Vigenere cipher("VIGENERECIPHER");
 
  string original = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
  string encrypted = cipher.encrypt(original);
  string decrypted = cipher.decrypt(encrypted);
 
  cout << original << endl;
  cout << "Encrypted: " << encrypted << endl;
  cout << "Decrypted: " << decrypted << endl;
}

thanks

Comments
Not easy start.

This is a very complex example if you are only learning. I'd suggest very basic programs to start out with like the infamous "Hello world". Also read some programmer books for beginners.

I've made only some ns2 scripts. Anyway, I know the vigenere cipher, but i don't understand how the algorithm works.

I've made only some ns2 scripts. Anyway, I know the vigenere cipher, but i don't understand how the algorithm works.

I'm not sure what exactly you mean by that; the cipher is the algorithm. Is there something specific about the code that is giving you trouble?

Here's a quick summary of what each function in the Vigenere class is doing:

  • Vigenere constructs a new cipher with the given key. All that if/else business makes it ignore parts of the key that aren't letters, and capitalizes everything.
  • encrypt does what it says on the box. More if/else to ignore characters that aren't letters and capitalize the ones that are. Note that the actual cipher is happening in the out += ... line; this is the algebraic version of the cipher.
  • Same goes for decrypt ; it's the algebraic version again.
This article has been dead for over six months. Start a new discussion instead.