Sunday, April 18, 2010

C++ exercises: tabular encrypt


Q: A string of text can be encrypted using a tabular mapping that associates each letter of the alphabet with a unique letter. For example, the mapping
   abcdefghijklmnopqrstuvwxyz ==> ngzqtcobmuhelkpdawxfyivrsj
maps "encrypt" to "tkzwsdf".
Write a program that reads text until end of file and outputs the encrypted form.

#include <iostream>
#include <string>
 
using namespace std;
 
int main()
{
   const char s[] = "abcdefghijklmnopqrstuvwxyz";
   const char d[] = "ngzqtcobmuhelkpdawxfyivrsj";
 
   while (1)
   {
      string st;
 
      cout << "Input a word: ";
      cin >> st;
      cout << endl << "Encrypted as: ";
 
      for (unsigned int i = 0; i < st.size(); i++)
      {
         for (unsigned int j = 0; j < sizeof(s); j++)
         {
            if (s[j] == st[i])
            {
               // found, output encrypted char
               cout << d[j];
            }
         }
      }

      cout << endl << endl;
   }

   return 0;
}

No comments:

 
Get This <