|
I'm trying to make a c++ program that encodes a message using the book cipher.
You get a message from a user, then you open a book from a txt file, and go thru it, matching randomly, a character that matches the character of the message, 1 by 1. so the message is coded in numbers. Then you give the message to the user. It would be row of numbers representing where the letter is in that book, from position 1, at the start of the book.
Here is what i have. I'm a beginner, and am kind of lost.
#include "stdafx.h"
#define _CRT_RAND_S
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
//Random Number generator
int randomNum ( unsigned vecSize ) {
unsigned number;
rand_s( &number );
double normalNum = static_cast<double>( number ) / UINT_MAX ;
return static_cast<unsigned>( normalNum * vecSize );
}//end random
//main program
int main( int argc, char* argv[] ) {
//Ask user for input for the words they want encoded
vector<char>message;
cout << "Please enter the message you want encoded here... " << endl;
cin >> message();
cout << "Message to be encoded: " << message << "\n";
//Create vectors and variables
vector<char>bookVector;
vector<char>codedMsg;
char messageCh, wapCh, randIndex;
bool unCh = false;
//open file and fill the book vector
ifstream wap;
wap.open("/forum/War_And_Peace.txt");
while (wap.get ( wapCh ))
{
if (wap.is_open()) {
while( wap.get( wapCh ) ) {
bookVector.push_back( wapCh );
}//end while
while( message.get( messageCh ) ) {
unsigned rand = randomNum( bookVector.size() - 1 );
unsigned randPos = rand;
randIndex = bookVector[randPos];
while( randIndex != messageCh ) {
++rand;
if ( rand == bookVector.size() -1 ) {
randIndex = bookVector[rand];
if ( randIndex == messageCh )
break;
else {
rand = 0;
randIndex = bookVector[rand];
}//end if
}//end if
if ( randIndex == messageCh )
break;
else if ( rand == randPos ) {
cout << messageCh << " char not in book!" << endl;
unCh = true;
break;
}//end if
else
randIndex = bookVector[rand];
}//end while
if ( !unCh )
codedMsg.push_back( rand );
else
break;
}//end while
if ( !unCh ) {
for(unsigned i = 0; i < codedMsg.size(); ++i)
out << codedMsg << '\n';//?
cout << "Message successfully coded." << endl;
}//end if
else cout << "Encoder didn't work.";
}//end while
}//end main
|
|
|
|
|
|
|
|