Skip to content

Instantly share code, notes, and snippets.

@RyanBreaker
Last active March 15, 2016 16:44
Show Gist options
  • Save RyanBreaker/71bceb1a2ea6394a2060 to your computer and use it in GitHub Desktop.
Save RyanBreaker/71bceb1a2ea6394a2060 to your computer and use it in GitHub Desktop.
//
// main.cpp
// cipher
//
// Created by Ryan Breaker on 3/14/16.
// Copyright © 2016 Ryan Breaker. All rights reserved.
//
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
const int NUM_LETTERS = 26;
const int CAESAR = (rand() % (NUM_LETTERS - 1)) + 1;
bool isUpperCase(char c) {
return (c >= 'A' && c <= 'Z');
}
bool isAlphabetic(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
void encrypt() {
string line, encrypted = "";
ifstream inFile("sample.txt");
ofstream outFile("cipher.txt");
for(int counter = 0; getline(inFile, line) && counter < 1500; counter++) {
for(int i = 0; i < line.length(); i++) {
unsigned char c = line[i];
if(!isAlphabetic(c)) {
encrypted += c;
continue;
}
c += CAESAR;
if(c > 'z' || (isUpperCase(c - CAESAR) && c > 'Z'))
c -= NUM_LETTERS;
encrypted += c;
}
encrypted += '\n';
}
cout << "The encrypted file is:\n";
cout << encrypted;
outFile << encrypted;
outFile.close();
inFile.close();
}
void decrypt() {
string decrypted = "";
ifstream inFile("cipher.txt");
ofstream outFile("result.txt");
for(string line; getline(inFile, line); ) {
for(int i = 0; i < line.length(); i++) {
unsigned char c = line[i];
if(!isAlphabetic(c)) {
decrypted += c;
continue;
}
c -= CAESAR;
if(c < 'A' || (!isUpperCase(c + CAESAR) && c < 'a'))
c += NUM_LETTERS;
decrypted += c;
}
decrypted += '\n';
}
cout << "The decrypted file is:\n";
cout << decrypted;
outFile << decrypted;
outFile.close();
inFile.close();
}
int main(int argc, const char * argv[]) {
short choice = 0;
bool invalidChoice = true;
//------------------------------
cout << "STUDENT INFO HERE\n\n";
//------------------------------
while(invalidChoice) {
cout << "Choose your option:\n";
cout << "1. Encrypt a file\n";
cout << "2. Decrypt a file\n";
cout << "Your choice: ";
cin >> choice;
if((invalidChoice = (choice < 1 || choice > 2))) {
cout << "\nInvalid input, please try again.\n";
}
}
if(choice == 1) {
cout << "You entered option 1 to encrypt file sample.txt\n";
encrypt();
return 0;
}
decrypt();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment