top of page

C++

Here is a collection of all the projects and code I wrote using C++

Advanced Encrypt/Decrypt

This project involved creating a script which reads from a file to then encrypt/decrypt it into a new file. The program will also print the statistics of the file such as the amount of characters, words, and lines.

// crypto.h

// Incrypting and Decrypting Data

// based on user input of a file,

// printing stats about the file,

// and saving run data into an output file.

// Author: Cody Luketic

#ifndef _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT2_TASK_1_CRYPTO_H_

#define _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT2_TASK_1_CRYPTO_H_

 

#include <iostream>

#include <fstream>

#include <vector>

#include <string>

#include <algorithm>

 

using std::cout;

using std::cin;

using std::cerr;

using std::endl;

using std::ifstream;

using std::ofstream;

using std::vector;

using std::string;

using std::transform;

 

// Given a char c return the encrypted character

char encrypt(char c);

// Given a char c retun the decrypted character

char decrypt(char c);

// Given a reference to an open file

// return a vector with the # of characters, words, lines

vector<int> stats(ifstream& infile);

// For seperation of elements.

void printALine();

// Simple Menu for user.

void printMenu();

// Returns user input of input file name.

string findInput();

// Returns user input of output file name.

string findOutput();

// Forces the user to choose a correct selection.

int findSelection();

// Checks if the file is available to open.

bool checkForFileError(string inputFile);

// Encrypts the inputFile information into the outputFile.

void encryptFile(string inputFile, string outputFile);

// Decrypts the inputFile information into the outputFile.

void decryptFile(string inputFile, string outputFile);

// Saves the file stats into a vector for printing.

void fileStats(string inputFile);

#endif  // _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT2_TASK_1_CRYPTO_H_

// crypto.cpp

// Incrypting and Decrypting Data

// based on user input of a file,

// printing stats about the file,

// and saving run data into an output file.

// Author: Cody Luketic

#include "./crypto.h"

 

// Given a char c return the encrypted character

char encrypt(char c) {

    return (c - 'A' + 5) % 26 + 'A';

}

 

// Given a char c return the decrypted character

char decrypt(char c) {

    return (c + 'A' - 5) % 26 + 'A';

}

 

// Given a reference to an open file,

// return a vector with the # of

// characters, words, and lines.

vector<int> stats(ifstream& infile) {

    vector<int> statistics;

    int characters = 0;

    int words = 0;

    int lines = 0;

 

    char current;

    string line = "";

 

    while (getline(infile, line)) {

        lines++;

        words++;

        int length = line.length();

 

        for (int i = 0; i < length; i++) {

            characters++;

            current = line[i];

            if (current == ' ') {

                words++;

            }

        }

    }

 

    statistics.push_back(characters);

    statistics.push_back(words);

    statistics.push_back(lines);

 

    return statistics;

}

 

// For seperation of elements.

void printALine() {

    cout << "----------------------------------------------\n";

}

 

// Simple Menu for user.

void printMenu() {

    cout << "Welcome to My Cryptographic Techniques\n\n";

    cout << "Please enter your selection:\n\n";

    cout << "   1. Encrypt\n";

    cout << "   2. Decrypt\n";

    cout << "   3. Exit \n\n";

    cout << "Selection: ";

}

 

// Returns user input of input file name.

string findInput() {

    string inputFile = "";

 

    cout << "Please enter an input file name: ";

    cin >> inputFile;

 

    return inputFile;

}

 

// Returns user input of output file name.

string findOutput() {

    string outputFile = "";

 

    cout << "Please enter an output file name: ";

    cin >> outputFile;

    cout << endl;

 

    return outputFile;

}

 

// Forces the user to choose a correct selection.

int findSelection() {

    int selection = 0;

 

    while (true) {

        printMenu();

 

        cin >> selection;

 

        if (selection < 1 || selection > 3) {

            cerr << "Incorrect Selection!\n";

            printALine();

        } else {

            return selection;

        }

    }

}

 

// Checks if the file is available to open.

bool checkForFileError(string inputFile) {

    ifstream input(inputFile);

 

    if (input.fail()) {

        cerr << "Could not open file\n";

        return true;

    }

 

    input.close();

 

    return false;

}

 

// Encrypts the inputFile information into the outputFile.

void encryptFile(string inputFile, string outputFile) {

    ifstream input(inputFile);

    ofstream output(outputFile);

 

    char current;

    string line = "";

 

    while (getline(input, line)) {

        transform(line.begin(), line.end(), line.begin(), ::toupper);

        int length = line.length();

 

        for (int i = 0; i < length; i++) {

            current = line[i];

            if ((current >= 'A' && current <= 'Z')

                || (current >= 'a' && current <= 'z')) {

                output << encrypt(line[i]);

            } else {

                output << line[i];

            }

        }

        output << endl;

    }

 

    input.close();

    output.close();

}

 

// Decrypts the inputFile information into the outputFile.

void decryptFile(string inputFile, string outputFile) {

    ifstream input(inputFile);

    ofstream output(outputFile);

 

    char current;

    string line = "";

 

    while (getline(input, line)) {

        int length = line.length();

 

        for (int i = 0; i < length; i++) {

            current = line[i];

            if ((current >= 'A' && current <= 'Z')

                || (current >= 'a' && current <= 'z')) {

                output << decrypt(line[i]);

            } else {

                output << line[i];

            }

        }

        output << endl;

    }

 

    input.close();

    output.close();

}

 

// Saves the file stats into a vector for printing.

void fileStats(string inputFile) {

    ifstream input(inputFile);

 

    vector<int> statistics = stats(input);

 

    cout << "The program has processed " << inputFile << endl;

    cout << "Characters: " << statistics.at(0) << endl;

    cout << "Words: " << statistics.at(1) << endl;

    cout << "Lines: " << statistics.at(2) << endl;

    printALine();

 

    input.close();

}

// cryptoapp.cpp

// Incrypting and Decrypting Data

// based on user input of a file,

// printing stats about the file,

// and saving run data into an output file.

// Author: Cody Luketic

#include "./crypto.h"

 

int main() {

    int selection = 0;

    bool fileError = false;

 

    string inputFile = "";

    string outputFile = "";

 

    while (true) {

        fileError = false;

        selection = findSelection();

        printALine();

 

        if (selection == 3) {

            exit(1);

        }

 

        inputFile = findInput();

        outputFile = findOutput();

 

        fileError = checkForFileError(inputFile);

 

        if (!fileError && selection == 2) {

            decryptFile(inputFile, outputFile);

        } else if (!fileError && selection == 1) {

            encryptFile(inputFile, outputFile);

        }

        printALine();

 

        if (!fileError) {

            fileStats(inputFile);

        }

    }

}

Monster Fighting Game

In this project I made a monster fighting game where the user creates an account and then will face off against increasingly difficult monsters. This also included a makefile for fast compiling of the scripts.

// meloniaHeader.h

// A Stat Battler game where you the player face off

// against increasingly powerful monsters. You must

// or else die against them while growing the health

// and damage stats on your saved profile.

// Author: Cody Luketic

#ifndef _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT2_TASK_2_MELONIAHEADER_H_

#define _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT2_TASK_2_MELONIAHEADER_H_

 

#include <iostream>

#include <fstream>

#include <string>

 

using std::cout;

using std::cin;

using std::cerr;

using std::endl;

using std::ofstream;

using std::ifstream;

using std::string;

 

// For seperation of elements.

void printALine();

// For creating a username.

string setUsername();

// For creating a password.

string setPassword();

// For finding an already made username/file.

string loginUsername();

// For finding an already made password

// that goes alongside the username.

string loginPassword();

// Checks to make sure the information given links

// to a file and that the password is correct.

bool checkInfoForError(string username, string password);

// Welcome to the world and finding if a new player or returning.

bool welcome();

// Describing to the player a basic world and gameplay plot.

void worldInformation(string username);

// The main menu showing the current stats

// and receiving the player's choice.

int battleMenu(int health, int damage, int monstHealth, int monstDamage);

// The player won text.

void victoryText(string username);

// The player lost text.

void deathText(string username);

#endif  // _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT2_TASK_2_MELONIAHEADER_H_

// melodiaFunctions.cpp

// A Stat Battler game where you the player face off

// against increasingly powerful monsters. You must

// or else die against them while growing the health

// and damage stats on your saved profile.

// Author: Cody Luketic

#include "./meloniaHeader.h"

 

// For seperation of elements.

void printALine() {

    cout << "-------------------------------"

        << "-------------------------------\n";

}

 

// For creating a username.

string setUsername() {

    string username = "";

 

    cout << "Please enter a username for yourself: ";

    cin >> username;

 

    return username;

}

 

// For creating a password.

string setPassword() {

    string password = "";

 

    cout << "Please enter a password: ";

    cin >> password;

 

    printALine();

 

    return password;

}

 

// For finding an already made username/file.

string loginUsername() {

    string username = "";

 

    cout << "Please enter your username: ";

    cin >> username;

 

    return username;

}

 

// For finding an already made password

// that goes alongside the username.

string loginPassword() {

    string password = "";

 

    cout << "Please enter your password: ";

    cin >> password;

 

    printALine();

 

    return password;

}

 

// Checks to make sure the information given links

// to a file and that the password is correct.

bool checkInfoForError(string username, string password) {

    ifstream profile(username + ".txt");

    string tempPas = "";

 

    if (profile.fail()) {

        cerr << "No user with this name, please try again\n";

        return true;

    }

 

    profile >> tempPas;

 

    if (tempPas != password) {

        cerr << "Incorrect password, please try again\n";

        return true;

    }

 

    return false;

}

 

// Welcome to the world and finding if a new player or returning.

bool welcome() {

    string type = "";

 

    cout << "Welcome to Melonia!\n\n"

        << "If you are a new player, type \'new\' now!\n"

        << "Or, if you are a returning player, type \'returning\' now!\n\n";

    cin >> type;

 

    printALine();

 

    while (true) {

        if (type == "new") {

            return true;

        } else if (type == "returning") {

            return false;

        } else {

            cerr << "Invalid Input, please try again.\n\n";

        }

    }

}

 

// Describing to the player a basic world and gameplay plot.

void worldInformation(string username) {

    cout << "Melonia, a world of terrifying monsters.\n"

        << "You " << username

        << " are tasked with destroying these creatures!\n"

        << "For every monster defeated,"

        << " you will grow stronger, but so will they.\n"

        << "Ready to battle? Well here comes a monster!\n";

 

    printALine();

}

 

// The main menu showing the current stats

// and receiving the player's choice.

int battleMenu(int health, int damage, int monstHealth, int monstDamage) {

    int choice = 0;

 

    cout << "Monster Health: " << monstHealth

        << "\nMonster Power: " << monstDamage

        << "\n\nYour Health: " << health

        << "\nYour Power: " << damage

        << endl << endl;

 

    cout << "Please choose your action by typing the corresponding number:\n"

        << "\t1. Attack Monster\n"

        << "\t2. Train Up\n"

        << "\t3. Run and Exit Game\n"

        << "Selection: ";

 

    cin >> choice;

 

    printALine();

 

    return choice;

}

 

// The player won text.

void victoryText(string username) {

    cout << username << " you defeated the monster!\n"

        << "Your damage has increased by 1, "

        << "but a new stronger monster approaches.\n";

 

    printALine();

}

 

// The player lost text.

void deathText(string username) {

    cout << username << " you have died!\n"

        << "I will not let this be your end.\n"

        << "Choose carefully next time!\n";

 

    printALine();

}

// meloniaApp.cpp

// A Stat Battler game where you the player face off

// against increasingly powerful monsters. You must

// or else die against them while growing the health

// and damage stats on your saved profile.

// Author: Cody Luketic

#include "./meloniaHeader.h"

 

int main() {

    bool isNew = true;

 

    string username = "";

    string password = "";

 

    int health = 10;

    int damage = 1;

    int monstHealth = 3;

    int monstDamage = 1;

 

    isNew = welcome();

 

    if (isNew) {

        username = setUsername();

        password = setPassword();

    } else {

        do {

            username = loginUsername();

            password = loginPassword();

        } while (checkInfoForError(username, password));

 

        ifstream profile(username + ".txt");

 

        string trash = "";

        profile >> trash;

 

        profile >> health;

        profile >> damage;

        profile >> monstHealth;

        profile >> monstDamage;

 

        profile.close();

    }

 

    ofstream profile(username + ".txt");

    profile << password << endl;

 

    worldInformation(username);

 

    int choice = 0;

    int tempHealth = health;

    int tempMonstHealth = monstHealth;

    do {

        choice = battleMenu(health, damage, monstHealth, monstDamage);

 

        if (choice == 1) {

            monstHealth -= damage;

            if (monstHealth <= 0) {

                victoryText(username);

                damage++;

                health = tempHealth;

 

                monstDamage += 3;

                monstHealth = tempMonstHealth + 3;

                tempMonstHealth = monstHealth;

            }

 

            health -= monstDamage;

            if (health <= 0) {

                deathText(username);

                health = tempHealth;

 

                monstHealth = tempMonstHealth;

            }

        } else if (choice == 2) {

            cout << "You have gained 1 more health!\n";

            printALine();

 

            health++;

            tempHealth++;

        }

    } while (choice != 3);

 

    cout << "Goodbye " << username << "! See you next time!\n";

 

    profile << health << endl;

    profile << damage << endl;

    profile << monstHealth << endl;

    profile << monstDamage << endl;

 

    profile.close();

}

Stat Game With Servers

I used a Cient/Server application with C++ Sockets for this project. I created scripts for both the client and the server and when running them together allows the user to play a game. The game involved increasing the player's stats by passing using the keyboard.

// PowerupHeadClient.h

// A Stat increasing game using a server to check the tests

// allowing a stat to be increased.

// Author: Cody Luketic

#ifndef _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT3_POWERUPHEADCLIENT_H_

#define _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT3_POWERUPHEADCLIENT_H_

 

#include <time.h>

#include <iostream>

#include <fstream>

#include <string>

#include "PracticalSocket.h"  // For Socket and SocketException

 

// For seperation of elements.

void printALine();

// For creating a username.

string setUsername();

// For creating a password.

string setPassword();

// For finding an already made username/file.

string loginUsername();

// For finding an already made password

// that goes alongside the username.

string loginPassword();

// Checks to make sure the information given links

// to a file and that the password is correct.

bool checkInfoForError(string username, string password);

// A welcome to the game and finds if user is a new or returning player.

bool welcome();

// An explanation of the game, options to choose, and the current stats.

void menu(int strength, int endurance, int speed, int intelligence);

// The main method involving all connections to the server

// and decisions on want is sent and recieved.

void serverConnection(string servAddress, unsigned short echoServPort);

 

#endif  // _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT3_POWERUPHEADCLIENT_H_

// PowerupFuncClient.cpp

// A Stat increasing game using a server to check the tests

// allowing a stat to be increased.

// Author: Cody Luketic

#include "./PowerupHeadClient.h"

 

// For seperation of elements.

void printALine() {

    cout << "-------------------------------"

        << "-------------------------------\n";

}

 

// For creating a username.

string setUsername() {

    string username = "";

 

    cout << "Please enter a username for yourself: ";

    cin >> username;

 

    return username;

}

 

// For creating a password.

string setPassword() {

    string password = "";

 

    cout << "Please enter a password: ";

    cin >> password;

 

    printALine();

 

    return password;

}

 

// For finding an already made username/file.

string loginUsername() {

    string username = "";

 

    cout << "Please enter your username: ";

    cin >> username;

 

    return username;

}

 

// For finding an already made password

// that goes alongside the username.

string loginPassword() {

    string password = "";

 

    cout << "Please enter your password: ";

    cin >> password;

 

    printALine();

 

    return password;

}

 

// Checks to make sure the information given links

// to a file and that the password is correct.

bool checkInfoForError(string username, string password) {

    ifstream profile(username + ".txt");

    string tempPas = "";

 

    if (profile.fail()) {

        cerr << "No user with this name, please try again\n";

        return true;

    }

 

    profile >> tempPas;

 

    if (tempPas != password) {

        cerr << "Incorrect password, please try again\n";

        return true;

    }

 

    return false;

}

 

// A welcome to the game and finds if user is a new or returning player.

bool welcome() {

    string type = "";

 

    cout << "Welcome to Powerup!\n\n"

        << "If you are a new player, type \'new\' now!\n"

        << "Or, if you are a returning player, type \'returning\' now!\n\n";

 

    while (true) {

        cin >> type;

 

        printALine();

 

        if (type == "new") {

            return true;

        } else if (type == "returning") {

            return false;

        } else {

            cerr << "Invalid Input, please try again.\n\n";

        }

    }

}

 

// An explanation of the game, options to choose, and the current stats.

void menu(int strength, int endurance, int speed, int intelligence) {

    cout << "This is Powerup, a game where your aim "

        << "is to become the best version "

        << "of yourself." << endl;

    cout << "To do this, you must pass the test for "

        << "each skill, slowly increasing them!" << endl;

    printALine();

    cout << "Here are your options and what they are currently at." << endl;

    cout << "1. Increase Strength | Current = " << strength << endl;

    cout << "2. Increase Endurance | Current = " << endurance << endl;

    cout << "3. Increase Speed | Current = " << speed << endl;

    cout << "4. Increase Intelligence | Current = " << intelligence << endl;

    cout << "What do you choose to do: ";

}

 

// The main method involving all connections to the server

// and decisions on want is sent and recieved.

void serverConnection(string servAddress, unsigned short echoServPort) {

    try {

        // Establish connection with the echo server

        TCPSocket sock(servAddress, echoServPort);

 

        int passcode1 = 0;

        int passcode2 = 0;

        int logged = 0;

        cout << "Please enter the "

            << "passcodes to the server." << endl;

 

        while (logged != 1) {

            cout << "Enter passcode 1: ";

            cin >> passcode1;

            cout << "Enter passcode 2: ";

            cin >> passcode2;

            printALine();

            sock.send(&passcode1, sizeof(passcode1));

            sock.send(&passcode2, sizeof(passcode2));

 

            sock.recv(&logged, sizeof(logged));

            if (logged != 1) {

                cout << "Incorrect, try again." << endl;

            }

            sock.send(&logged, sizeof(logged));

        }

 

        bool isNew = welcome();

        string username = "";

        string password = "";

        int strength = 1;

        int endurance = 1;

        int speed = 1;

        int intelligence = 1;

        if (isNew) {

            username = setUsername();

            password = setPassword();

        } else {

            do {

                username = loginUsername();

                password = loginPassword();

            } while (checkInfoForError(username, password));

 

            ifstream profile(username + ".txt");

 

            string trash = "";

            profile >> trash;

 

            profile >> strength;

            profile >> endurance;

            profile >> speed;

            profile >> intelligence;

 

            profile.close();

        }

 

        int choice = 0;

        int result = 0;

        int count = 0;

        int temp = 0;

        int tempRand1 = 0;

        menu(strength, endurance, speed, intelligence);

 

        cin >> choice;

        printALine();

 

        sock.send(&choice, sizeof(choice));

        switch (choice) {

            case 1:

                sock.send(&strength, sizeof(strength));

 

                cout << "To increase your Strength, type "

                    << "and enter the numbers 1-10." << endl;

 

                while (count < 10) {

                    cin >> temp;

                    sock.send(&temp, sizeof(temp));

                    count++;

                }

                break;

            case 2:

                sock.send(&endurance, sizeof(endurance));

 

                cout << "To increase your Endurance, type "

                    << "and enter '1234' continuously." << endl;

 

                while (count < endurance) {

                    cin >> temp;

                    printALine();

 

                    sock.send(&temp, sizeof(temp));

                    count++;

                }

                sock.send(&endurance, sizeof(endurance));

                break;

            case 3:

                sock.send(&speed, sizeof(speed));

 

                cout << "To increase your Speed, type "

                    << "and enter '1' " << 5 + speed

                    << " times." << endl;

 

                while (count < 5 + speed) {

                    cin >> temp;

                    sock.send(&temp, sizeof(temp));

                    count++;

                }

                break;

            case 4:

                sock.send(&intelligence, sizeof(intelligence));

 

                srand(time(NULL));

                tempRand1 = rand() % intelligence + 2;

 

                cout << "To increase your Intelligence, type "

                    << "and enter the product of "

                    << tempRand1 << " * " << intelligence

                    << "." << endl;

                cin >> temp;

 

                sock.send(&temp, sizeof(temp));

                sock.send(&tempRand1, sizeof(tempRand1));

                sock.send(&intelligence, sizeof(intelligence));

                break;

            default:

                cout << "Invalid Choice." << endl;

                break;

        }

        printALine();

 

        sock.recv(&result, sizeof(result));

        if (result == 0) {

            cout << "You failed the action "

                << "and did not increase your stat." << endl;

        } else {

            switch (choice) {

                case 1:

                    cout << "Your Strength was raised to: " << result << endl;

                    strength = result;

                    break;

                case 2:

                    cout << "Your Endurance was raised to: " << result << endl;

                    endurance = result;

                    break;

                case 3:

                    cout << "Your Speed was raised to: " << result << endl;

                    speed = result;

                    break;

                case 4:

                    cout << "Your Intelligence was raised to: "

                        << result << endl;

                    intelligence = result;

                    break;

                default:

                    cout << "Invalid Choice" << endl;

                    break;

            }

        }

 

        ofstream profile(username + ".txt");

        profile << password << endl;

        profile << strength << endl;

        profile << endurance << endl;

        profile << speed << endl;

        profile << intelligence << endl;

        profile.close();

    } catch(std::exception &e) {

        cerr << e.what() << endl;

        exit(1);

    }

}

/*

 *   C++ sockets on Unix and Windows

 *   Copyright (C) 2002

 *

 *   This program is free software; you can redistribute it and/or modify

 *   it under the terms of the GNU General Public License as published by

 *   the Free Software Foundation; either version 2 of the License, or

 *   (at your option) any later version.

 *

 *   This program is distributed in the hope that it will be useful,

 *   but WITHOUT ANY WARRANTY; without even the implied warranty of

 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

 *   GNU General Public License for more details.

 *

 *   You should have received a copy of the GNU General Public License

 *   along with this program; if not, write to the Free Software

 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 */

 

// Code modified by Qusay Mahmoud to address dynamic

// exception specifications which are deprecated since C++11

// PowerupClient.cpp

// A Stat increasing game using a server to check the tests

// allowing a stat to be increased.

// Author: Cody Luketic

 

#include "./PowerupHeadClient.h"

 

int main(int argc, char *argv[]) {

    if (argc != 3) {  // Test for correct number of arguments

        cerr << "Usage: " << argv[0]

             << " <Server Name> <Server Port#>" << endl;

        exit(1);

    }

 

    string servAddress = argv[1];  // First arg: server address

    int16_t echoServPort = (atoi(argv[2]));  // Second arg: server port

 

    serverConnection(servAddress, echoServPort);

 

    return(0);

}

// PowerupHeadServer.h

// A Stat increasing game using a server to check the tests

// allowing a stat to be increased.

// Author: Cody Luketic

#ifndef _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT3_POWERUPHEADSERVER_H_

#define _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT3_POWERUPHEADSERVER_H_

 

#include <iostream>

#include "PracticalSocket.h"  // For Socket, ServerSocket, and SocketException

 

// For seperation of elements.

void printALine();

// Print information about connected client.

void clientInfo(TCPSocket *sock);

// Check to make sure user is authorized using passcodes.

void checkPasscode(TCPSocket *sock);

// TCP client handling function.

void HandleTCPClient(TCPSocket *sock);

 

#endif  // _HOME_CODYL_CSE278_ASSIGNMENTS_ASSIGNMENT3_POWERUPHEADSERVER_H_

// PowerupFuncServer.cpp

 

// A Stat increasing game using a server to check the tests

// allowing a stat to be increased.

// Author: Cody Luketic

#include "./PowerupHeadServer.h"

 

// For seperation of elements.

void printALine() {

    cout << "-------------------------------"

        << "-------------------------------\n";

}

 

// Print information about connected client.

void clientInfo(TCPSocket *sock) {

    cout << "Handling client ";

    try {

        cout << sock->getForeignAddress() << ":";

    } catch (const std::exception& e) {

        cerr << "Unable to get foreign address" << endl;

        cerr << e.what() << endl;

    }

    try {

        cout << sock->getForeignPort();

    } catch (const std::exception& e) {

        cerr << "Unable to get foreign port" << endl;

        cerr << e.what() << endl;

    }

    cout << endl;

}

 

// Check to make sure user is authorized using passcodes.

void checkPasscode(TCPSocket *sock) {

    int contin = 0;

    while (contin != 1) {

        int passcode1 = 0;

        int passcode2 = 0;

        int passed = 0;

        sock->recv(&passcode1, sizeof(passcode1));

        sock->recv(&passcode2, sizeof(passcode2));

 

        if (passcode1 == 678 || passcode2 == 14965) {

            passed = 1;

        }

        sock->send(&passed, sizeof(passed));

        sock->recv(&contin, sizeof(contin));

    }

}

 

// TCP client handling function.

void HandleTCPClient(TCPSocket *sock) {

    clientInfo(sock);

 

    checkPasscode(sock);

 

    int result = 0;

    int current = 0;

    int choice = 0;

    int test = 0;

    int testRand1 = 0;

    int testRand2 = 0;

    int count = 0;

 

    int choiceBytes = sock->recv(&choice, sizeof(choice));

    int currentBytes = sock->recv(&current, sizeof(current));

 

    cout << "Choice Bytes = " << choiceBytes << endl;

    cout << "Current Bytes = " << currentBytes << endl;

    printALine();

    cout << "Choice = " << choice << endl;

    printALine();

    switch (choice) {

        case 1:

            result = -10;

            count++;

            while (count < 11) {

                sock->recv(&test, sizeof(test));

                cout << "Test = " << test << endl;

                if (test != count) {

                    cout << "Incorrect number!" << endl;

                } else {

                    result++;

                }

                count++;

            }

            break;

        case 2:

            result = -current;

            while (count < current) {

                sock->recv(&test, sizeof(test));

                cout << "Test = " << test << endl;

                if (test != 1234) {

                    cout << "Incorrect number!" << endl;

                } else {

                    result++;

                }

                count++;

            }

            break;

        case 3:

            result = -5 - current;

            while (count < 5 + current) {

                sock->recv(&test, sizeof(test));

                cout << "Test = " << test << endl;

                if (test != 1) {

                    cout << "Incorrect number!" << endl;

                } else {

                    result++;

                }

                count++;

            }

            break;

        case 4:

            sock->recv(&test, sizeof(test));

            sock->recv(&testRand1, sizeof(testRand1));

            sock->recv(&testRand2, sizeof(testRand2));

            cout << "Test = " << test << endl;

            cout << "TestRand1 = " << testRand1 << endl;

            cout << "TestRand2 = " << testRand2 << endl;

 

            if (test != testRand1 * testRand2) {

                cout << "Incorrect answer!" << endl;

                result = -1;

            }

            break;

        default:

            cout << "Invalid Choice" << endl;

            break;

    }

    printALine();

    cout << "Current = " << current << endl;

    cout << "Result = " << result << endl;

 

    if (result == 0) {

        result = current + 1;

    } else {

        result = 0;

    }

    sock->send(&result, sizeof(result));

    printALine();

 

    delete sock;

}

/*

 *   C++ sockets on Unix and Windows

 *   Copyright (C) 2002

 *

 *   This program is free software; you can redistribute it and/or modify

 *   it under the terms of the GNU General Public License as published by

 *   the Free Software Foundation; either version 2 of the License, or

 *   (at your option) any later version.

 *

 *   This program is distributed in the hope that it will be useful,

 *   but WITHOUT ANY WARRANTY; without even the implied warranty of

 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the

 *   GNU General Public License for more details.

 *

 *   You should have received a copy of the GNU General Public License

 *   along with this program; if not, write to the Free Software

 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

 */

 

// Code modified by Qusay Mahmoud to address dynamic exception

// specifications which are deprecated since C++11

// PowerupServer.cpp

// A Stat increasing game using a server to check the tests

// allowing a stat to be increased.

// Author: Cody Luketic

 

#include "./PowerupHeadServer.h"

 

int main(int argc, char *argv[]) {

    if (argc != 2) {  // Test for correct number of arguments

        cerr << "Usage: " << argv[0] << " <Server Port>" << endl;

        exit(1);

    }

 

    int16_t echoServPort = atoi(argv[1]);  // First arg: local port

 

    try {

        TCPServerSocket servSock(echoServPort);  // Server Socket object

 

        for (;;) {   // Run forever

            HandleTCPClient(servSock.accept());  // Wait for a client to connect

        }

    } catch (const std::exception& e) {

        cerr << e.what() << endl;

        exit(1);

    }

 

    return(0);

}

// Makefile for Powerup.

powerup-Server: PowerupFuncServer.o

    g++ -Wall -o PowerupServer PowerupServer.cpp PracticalSocket.o PowerupFuncServer.o

powerupFuncServer.o: PowerupFuncServer.cpp PowerupHeadServer.h

    g++ -Wall -c PowerupFuncServer.cpp

 

powerup-Client: PowerupFuncClient.o

    g++ -Wall -o PowerupClient PowerupClient.cpp PracticalSocket.o PowerupFuncClient.o

powerupFuncClient.o: PowerupFuncClient.cpp PowerupHeadClient.h

    g++ -Wall -c PowerupFuncClient.cpp

 

clean:

    rm *.o

 

cpplint-Server: PowerupServer

    cpplint PowerupHeadServer.h PowerupFuncServer.cpp PowerupServer.cpp

    cpplint --filter=-build/include_subdir PowerupServer.cpp

 

cpplint-Client: PowerupClient

    cpplint PowerupHeadClient.h PowerupFuncClient.cpp PowerupClient.cpp

    cpplint --filter=-build/include_subdir PowerupClient.cpp

 

run-Server: PowerupServer

    ./PowerupServer 5000

 

run-Client: PowerupClient

    ./PowerupClient localhost 5000

MYSQL Story Website

My largest project with an aim to use MYSQL and .cgi scripts to create a website using HTML, CSS, and C++ code. I decided to make a story sharing site where users create an account or login to an existing one. This information is saved into a MYSQL table of users. The users can then write stories, read stories, edit stories, write reviews, and read reviews. All of this data is also saved into two more tables being stories and reviews respectively.

LandingPage.png
Application.png

/* createAccount.cpp

 * Recieves a name, email, country, and password from the user

 * to create a new account saved in a mysql table named luketicaUsers.

 * Author: Cody Luketic

 * Orginal Code: Qusay Mahmoud

 */

 

#define MYSQLPP_MYSQL_HEADERS_BURIED

#include <mysql++/mysql++.h>

#include <string>

#include <iostream>

#include "getpost.h"

 

using namespace std;

 

int main(int argc, char* argv[]) {

    map<string,string> Get;

    initializePost(Get);

 

    cout << "Content-type: text/html" << endl << endl;

    cout << "<html><body><center>" << endl;

 

    std::string name;

    std::string email;

    std::string country;

    std::string password;

 

    if (Get.find("name") != Get.end() && Get.find("email") != Get.end()

        && Get.find("password") !=Get.end() && Get.find("country") !=Get.end()) {

        name = Get["name"];

        email = Get["email"];

        country = Get["country"];

        password = Get["password"];

    } else {

        cout << "<p>Error filling out form, please try again!</p><br>" << endl;

        cout << "<p><a href = \"./LandingPage.html\">Return to Login</a></p>" << endl;

        cout << "</center></body></html>" << endl;

       

        return(1);

    }

 

    // Connect to database with: database, server, userID, password

    mysqlpp::Connection conn(false); // Exceptions suppressed to keep code simple

    if(conn.connect("cse278", "localhost", "cse278", "MonSepM1am1")) {

 

        // Create a query

        mysqlpp::Query query = conn.query();

 

        query << "INSERT into luketicaUsers (name, email, country, password) VALUES('"+name+"', '"+email+"', '"+country+"', '"+password+"');";

 

        query.parse();  // check to ensure it is correct

 

        mysqlpp::SimpleResult result = query.execute();

           

        if(result) {

            cout << "<h1>Welcome "+name+"! Click this link to the start creating, reading, and reviewing countless stories!</h1><br>" << endl;

            cout << "<h2><a href = \"./Application.html\">To Writing</a></h2>" << endl;

            cout << "</center></body></html>" << endl;

        } else {

            cout << "<p>Error filling out form, please try again!</p><br>" << endl;

            cout << "<p><a href = \"./LandingPage.html\">Return to Login</a></p>" << endl;

            cout << "</center></body></html>" << endl;

 

            return(1);

        }

        return(0);

    } else {

        cerr << "Connection failed: " << conn.error() <<endl;

        return(1);

    }

}

/* loginAccount.cpp

 * Recieves a name, and password from the user

 * to login to a current account and access the site.

 * Author: Cody Luketic

 * Orginal Code: Qusay Mahmoud

 */

 

#define MYSQLPP_MYSQL_HEADERS_BURIED

#include <mysql++/mysql++.h>

#include <string>

#include <iostream>

#include "getpost.h"

 

using namespace std;

 

int main(int argc, char* argv[]) {

    map<string,string> Get;

    initializePost(Get);

 

    cout << "Content-type: text/html" << endl << endl;

    cout << "<html><body><center>" << endl;

 

    std::string name;

    std::string password;

 

    if (Get.find("name") != Get.end() && Get.find("password") != Get.end()) {

        name = Get["name"];

        password = Get["password"];

    } else {

        cout << "<p>Error filling out form, please try again!</p><br>" << endl;

        cout << "<p><a href = \"./LandingPage.html\">Return to Login</a></p>" << endl;

        cout << "</center></body></html>" << endl;

       

        return(1);

    }

 

    // Connect to database with: database, server, userID, password

    mysqlpp::Connection conn(false); // Exceptions suppressed to keep code simple

    if(conn.connect("cse278", "localhost", "cse278", "MonSepM1am1")) {

 

        // Create a query

        mysqlpp::Query query = conn.query();

 

        query << "SELECT * FROM luketicaUsers WHERE name='"+name+"' AND password='"+password+"';";

 

        query.parse();  // check to ensure it is correct

 

        mysqlpp::StoreQueryResult result = query.store();

           

        if(result) {

            cout << "<h1>Welcome "+name+"! Click this link to the start creating, reading, and reviewing countless stories!</h1><br>" << endl;

            cout << "<h2><a href = \"./Application.html\">To Writing</a></h2>" << endl;

            cout << "</center></body></html>" << endl;

        } else {

            cout << "<p>Error, there is no user with this information, please try again!</p><br>" << endl;

            cout << "<p><a href = \"./LandingPage.html\">Return to Login</a></p>" << endl;

            cout << "</center></body></html>" << endl;

 

            return(1);

        }

        return(0);

    } else {

        cerr << "Connection failed: " << conn.error() <<endl;

        return(1);

    }

}

/* editStory.cpp

 * Recieves a title and story from the user

 * to edit an old story in a mysql table named luketicaStories.

 * Author: Cody Luketic

 * Orginal Code: Qusay Mahmoud

 */

 

#define MYSQLPP_MYSQL_HEADERS_BURIED

#include <mysql++/mysql++.h>

#include <string>

#include <iostream>

#include "getpost.h"

 

using namespace std;

 

int main(int argc, char* argv[]) {

    map<string,string> Get;

    initializePost(Get);

 

    cout << "Content-type: text/html" << endl << endl;

    cout << "<html><body><center>" << endl;

 

    std::string title;

    std::string story;

 

    if (Get.find("title") != Get.end() && Get.find("story") != Get.end()) {

        title = Get["title"];

        story = Get["story"];

    } else {

        cout << "<p>Error filling out information, please try again!</p><br>" << endl;

        cout << "<p><a href = \"./Application.html\">Return Home</a></p>" << endl;

        cout << "</center></body></html>" << endl;

       

        return(1);

    }

 

    // Connect to database with: database, server, userID, password

    mysqlpp::Connection conn(false); // Exceptions suppressed to keep code simple

    if(conn.connect("cse278", "localhost", "cse278", "MonSepM1am1")) {

        // Create a query

        mysqlpp::Query query = conn.query();

 

        query << "UPDATE luketicaStories SET story = '"+story+"' WHERE title = '"+title+"';";

 

        query.parse();  // check to ensure it is correct

 

        mysqlpp::SimpleResult result = query.execute();

           

        if(result) {

            cout << "<h1>The Story was Updated! Return home to view or invite others to review this story.</h1><br>" << endl;

            cout << "<h2><a href = \"./Application.html\">Return to Home</a></h2>" << endl;

            cout << "</center></body></html>" << endl;

        } else {

            cout << "<p>Error filling out information, please try again!</p><br>" << endl;

            cout << "<p><a href = \"./Application.html\">Return Home</a></p>" << endl;

            cout << "</center></body></html>" << endl;

           

            return(1);

        }

       

        return(0);

    } else {

        cerr << "Connection failed: " << conn.error() <<endl;

        return(1);

    }

}

/* publishStory.cpp

 * Recieves a name, title, and story from the user

 * to publish a new story saved in a mysql table named luketicaStories.

 * Author: Cody Luketic

 * Orginal Code: Qusay Mahmoud

 */

 

#define MYSQLPP_MYSQL_HEADERS_BURIED

#include <mysql++/mysql++.h>

#include <string>

#include <iostream>

#include "getpost.h"

 

using namespace std;

 

int main(int argc, char* argv[]) {

    map<string,string> Get;

    initializePost(Get);

   

    cout << "Content-type: text/html" << endl << endl;

    cout << "<html><body><center>" << endl;

 

    std::string name;

    std::string title;

    std::string story;

 

    if (Get.find("name") != Get.end() && Get.find("title") != Get.end()

        && Get.find("story") != Get.end()) {

        name = Get["name"];

        title = Get["title"];

        story = Get["story"];

    } else {

        cout << "<p>Error filling out information, please try again!</p><br>" << endl;

        cout << "<p><a href = \"./Application.html\">Return Home</a></p>" << endl;

        cout << "</center></body></html>" << endl;

       

        return(1);

    }

 

    // Connect to database with: database, server, userID, password

    mysqlpp::Connection conn(false); // Exceptions suppressed to keep code simple

    if(conn.connect("cse278", "localhost", "cse278", "MonSepM1am1")) {

        int id = -1;

 

        // Create a query

        mysqlpp::Query query = conn.query();

 

        query << "SELECT * FROM luketicaUsers WHERE name = '"+name+"';";

 

        query.parse();  // check to ensure it is correct

 

        mysqlpp::StoreQueryResult result = query.store();

           

        if(result) {

            id = result[0]["id"];

        } else {

            cout << "<p>There is no user with the name '"+name+"'. Please try again!</p><br>" << endl;

            cout << "<p><a href = \"./Application.html\">Return to Home</a></p>" << endl;

            cout << "</center></body></html>" << endl;

 

            return(1);

        }

        string sID = std::to_string(id);

       

        // Create a query

        mysqlpp::Query query2 = conn.query();

 

        query2 << "INSERT into luketicaStories (id, name, title, story) VALUES('"+sID+"', '"+name+"', '"+title+"', '"+story+"');";

 

        query2.parse();  // check to ensure it is correct

 

        mysqlpp::SimpleResult result2 = query2.execute();

           

        if(result2) {

            cout << "<h1>Your Story was Published! Return home to view or invite others to review your story.</h1><br>" << endl;

            cout << "<h2><a href = \"./Application.html\">Return to Home</a></h2>" << endl;

            cout << "</center></body></html>" << endl;

        } else {

            cout << "<p>Error filling out information, please try again!</p><br>" << endl;

            cout << "<p><a href = \"./Application.html\">Return to Home</a></p>" << endl;

            cout << "</center></body></html>" << endl;

 

            return(1);

        }

       

        return(0);

    } else {

        cerr << "Connection failed: " << conn.error() <<endl;

        return(1);

    }

}

/* readStories.cpp

 * Recieves a name from the user

 * to return a table of stories by that user.

 * Author: Cody Luketic

 * Orginal Code: Qusay Mahmoud

 */

 

#define MYSQLPP_MYSQL_HEADERS_BURIED

#include <mysql++/mysql++.h>

#include <string>

#include <iostream>

#include "getpost.h"

 

using namespace std;

 

int main(int argc, char* argv[]) {

    map<string,string> Get;

    initializePost(Get);

 

    cout << "Content-type: text/html" << endl << endl;

    cout << "<html><body><center>" << endl;

 

    std::string name;

 

    if (Get.find("name") != Get.end()) {

        name = Get["name"];

    } else {

        cout << "<p>Error filling out information, please try again!</p><br>" << endl;

        cout << "<p><a href = \"./Application.html\">Return Home</a></p>" << endl;

        cout << "</center></body></html>" << endl;

       

        return(1);

    }

 

    // Connect to database with: database, server, userID, password

    mysqlpp::Connection conn(false); // Exceptions suppressed to keep code simple

    if(conn.connect("cse278", "localhost", "cse278", "MonSepM1am1")) {

 

        // Create a query

        mysqlpp::Query query = conn.query();

 

        query << "SELECT * FROM luketicaStories WHERE name = '"+name+"';";

 

        query.parse();  // check to ensure it is correct

 

        mysqlpp::StoreQueryResult result = query.store();

           

        if(result) {

            cout << "<table border=1 width=600><tr><th>Title</th><th>Story</th>\n";

            for(int i = 0; i < result.num_rows(); ++i) {

                cout << "<tr><td>" << result[i]["title"] << "</td>"

                << "<td>" << result[i]["story"] << "</td></tr>"

                << endl;

            }

            cout << "</table><h2><a href = \"./Application.html\">Return to Home</a></h2>" << endl;

            cout << "</center></body></html>\n";

        } else {

            cout << "<p>There are no stories from '"+name+"'. Please try again!</p><br>" << endl;

            cout << "<p><a href = \"./Application.html\">Return to Home</a></p>" << endl;

            cout << "</center></body></html>" << endl;

 

            return(1);

        }

        return(0);

    } else {

        cerr << "Connection failed: " << conn.error() <<endl;

        return(1);

    }

}

/* writeReview.cpp

 * Recieves a name, storyTitle, reviewTitle and review

 * from the user to write a review of the story which

 * is then saved in a mysql table named luketicaReviews.

 * Author: Cody Luketic

 * Orginal Code: Qusay Mahmoud

 */

 

#define MYSQLPP_MYSQL_HEADERS_BURIED

#include <mysql++/mysql++.h>

#include <string>

#include <iostream>

#include "getpost.h"

 

using namespace std;

 

int main(int argc, char* argv[]) {

    map<string,string> Get;

    initializePost(Get);

 

    cout << "Content-type: text/html" << endl << endl;

    cout << "<html><body><center>" << endl;

 

    std::string name;

    std::string storyTitle;

    std::string reviewTitle;

    std::string review;

 

    if (Get.find("name") != Get.end() && Get.find("storyTitle") != Get.end()

        && Get.find("reviewTitle") != Get.end() && Get.find("review") != Get.end()) {

        name = Get["name"];

        storyTitle = Get["storyTitle"];

        reviewTitle = Get["reviewTitle"];

        review = Get["review"];

    } else {

        cout << "<p>Error filling out information, please try again!</p><br>" << endl;

        cout << "<p><a href = \"./Application.html\">Return Home</a></p>" << endl;

        cout << "</center></body></html>" << endl;

       

        return(1);

    }

 

    // Connect to database with: database, server, userID, password

    mysqlpp::Connection conn(false); // Exceptions suppressed to keep code simple

    if(conn.connect("cse278", "localhost", "cse278", "MonSepM1am1")) {

        int id = -1;

 

        // Create a query

        mysqlpp::Query query = conn.query();

 

        // Make name unique

        query << "SELECT * FROM luketicaUsers WHERE name = '"+name+"';";

 

        query.parse();  // check to ensure it is correct

 

        mysqlpp::StoreQueryResult result = query.store();

           

        if(result) {

            id = result[0]["id"];

        } else {

            cout << "<p>There is no user with the name '"+name+"'. Please try again!</p><br>" << endl;

            cout << "<p><a href = \"./Application.html\">Return to Home</a></p>" << endl;

            cout << "</center></body></html>" << endl;

 

            return(1);

        }

        string sID = std::to_string(id);

       

        // Create a query

        mysqlpp::Query query2 = conn.query();

 

        query2 << "INSERT into luketicaReviews (id, name, storyTitle, reviewTitle, review) VALUES('"+sID+"', '"+name+"', '"+storyTitle+"', '"+reviewTitle+"', '"+review+"');";

 

        query2.parse();  // check to ensure it is correct

 

        mysqlpp::SimpleResult result2 = query2.execute();

           

        if(result2) {

            cout << "<h1>Your Review was Submitted! Return home to view or write your own story.</h1><br>" << endl;

            cout << "<h2><a href = \"./Application.html\">Return to Home</a></h2>" << endl;

            cout << "</center></body></html>" << endl;

        } else {

            cout << "<p>Error filling out information, please try again!</p><br>" << endl;

            cout << "<p><a href = \"./Application.html\">Return to Home</a></p>" << endl;

            cout << "</center></body></html>" << endl;

           

            return(1);

        }

       

        return(0);

    } else {

        cerr << "Connection failed: " << conn.error() <<endl;

        return(1);

    }

}

/* readReviews.cpp

 * Recieves a title from the user

 * to return a table of reviews for it.

 * Author: Cody Luketic

 * Orginal Code: Qusay Mahmoud

 */

 

#define MYSQLPP_MYSQL_HEADERS_BURIED

#include <mysql++/mysql++.h>

#include <string>

#include <iostream>

#include "getpost.h"

 

using namespace std;

 

int main(int argc, char* argv[]) {

    map<string,string> Get;

    initializePost(Get);

 

    cout << "Content-type: text/html" << endl << endl;

    cout << "<html><body><center>" << endl;

 

    std::string title;

 

    if (Get.find("title") != Get.end()) {

        title = Get["title"];

    } else {

        cout << "<p>Error filling out information, please try again!</p><br>" << endl;

        cout << "<p><a href = \"./Application.html\">Return Home</a></p>" << endl;

        cout << "</center></body></html>" << endl;

       

        return(1);

    }

 

    // Connect to database with: database, server, userID, password

    mysqlpp::Connection conn(false); // Exceptions suppressed to keep code simple

    if(conn.connect("cse278", "localhost", "cse278", "MonSepM1am1")) {

 

        // Create a query

        mysqlpp::Query query = conn.query();

 

        query << "SELECT * FROM luketicaReviews WHERE storyTitle = '"+title+"';";

 

        query.parse();  // check to ensure it is correct

 

        mysqlpp::StoreQueryResult result = query.store();

           

        if(result) {

            cout << "<table border=1 width=600><tr><th>Review Title</th><th>Review</th>\n";

            for(int i = 0; i < result.num_rows(); ++i) {

                cout << "<tr><td>" << result[i]["reviewTitle"] << "</td>"

                << "<td>" << result[i]["review"] << "</td></tr>"

                << endl;

            }

            cout << "</table><h2><a href = \"./Application.html\">Return to Home</a></h2>" << endl;

            cout << "</center></body></html>\n";

        } else {

            cout << "<p>Error, there are no reviews for this story, please try again!</p><br>" << endl;

            cout << "<p><a href = \"./Application.html\">Return to Home</a></p>" << endl;

            cout << "</center></body></html>" << endl;

        }

        return(0);

    } else {

        cerr << "Connection failed: " << conn.error() <<endl;

        return(1);

    }

}

bottom of page