Keyword Cipher | CPP program for encoding the string using classical cipher ; Function generates the encoded text ; This array represents the 26 letters of alphabets ; This loop inserts the keyword at the start of the encoded string ; To check whether the character is inserted earlier in the encoded string or not ; This loop inserts the remaining characters in the encoded string . ; Function that generates encodes ( cipher ) the message ; This loop ciphered the message . Spaces , special characters and numbers remain same . ; Driver code ; Hold the Keyword ; Function call to generate encoded text ; Message that need to encode ; Function call to print ciphered text
#include <bits/stdc++.h> NEW_LINE using namespace std ; string encoder ( string key ) { string encoded = " " ; bool arr [ 26 ] = { 0 } ; for ( int i = 0 ; i < key . size ( ) ; i ++ ) { if ( key [ i ] >= ' A ' && key [ i ] <= ' Z ' ) { if ( arr [ key [ i ] - 65 ] == 0 ) { encoded += key [ i ] ; arr [ key [ i ] - 65 ] = 1 ; } } else if ( key [ i ] >= ' a ' && key [ i ] <= ' z ' ) { if ( arr [ key [ i ] - 97 ] == 0 ) { encoded += key [ i ] - 32 ; arr [ key [ i ] - 97 ] = 1 ; } } } for ( int i = 0 ; i < 26 ; i ++ ) { if ( arr [ i ] == 0 ) { arr [ i ] = 1 ; encoded += char ( i + 65 ) ; } } return encoded ; } string cipheredIt ( string msg , string encoded ) { string cipher = " " ; for ( int i = 0 ; i < msg . size ( ) ; i ++ ) { if ( msg [ i ] >= ' a ' && msg [ i ] <= ' z ' ) { int pos = msg [ i ] - 97 ; cipher += encoded [ pos ] ; } else if ( msg [ i ] >= ' A ' && msg [ i ] <= ' Z ' ) { int pos = msg [ i ] - 65 ; cipher += encoded [ pos ] ; } else { cipher += msg [ i ] ; } } return cipher ; } int main ( ) { string key ; key = " Computer " ; cout << " Keyword ▁ : ▁ " << key << endl ; string encoded = encoder ( key ) ; string message = " GeeksforGeeks " ; cout << " Message ▁ before ▁ Ciphering ▁ : ▁ " << message << endl ; cout << " Ciphered ▁ Text ▁ : ▁ " << cipheredIt ( message , encoded ) << endl ; return 0 ; }