Strange output when using atof(optarg) - c++

Edit::
Resolved- This was due to a misunderstanding of the use of the getOpt function.
I referenced the materials in the man here, on stack overflow (http://linux.die.net/man/3/getopt) and the getOpt documentation on GNU's website here: gnu.org/software/libc/manual/html_node/Example-of-Getopt.html Thanks to Bill Lynch and Remyabel for referencing source materials previously mentioned.
there seems to be an issue when I run this program using the -f variable to run the "Football" Commands, alongside using -c, However, I'm primarily concerned on getting just one to work for now.
Placing in the input:
-f -p 16 -a 25 -y 267 -t 1 -i 2
Gives out::
pC = 0
pC = 32738
pY = -1052776240
T = 32738
I = 1
Now, these variables should just be spitting out exactly what I put in, as the only conversion I'm using ( as seen below) is X = atof(optarg);
I suspect this may have something to do with the ASCII values, though I'm almost entirely clueless.
#
#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <time.h>
#include <stdlib.h>
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
srand(time(NULL));
double r = (6 + ( std::rand() % ( 8 - 6 + 1 ) )) / 10;
int c;
int pA;
int pY;
int T;
int I;
int pC;
double mass;
double bMass;
double dist;
double velo;
double Cr = .001;
double k = .18;
double g = 9.8;
double CFdraft;
double Pair;
double Proll;
double Psec;
double timeTravel = 0.0;
double Et;
double E;
double Eavg = 0;
int x = 0;
double cT;
double cC;
double cY;
double cI;
double PasserRating;
while ((c = getopt (argc, argv, "c:m:b:v:d:f:p:a:y:t:i:")) != -1)
{
if (c == 'f') // There seems to be some kind of misunderstanding with what this is doing
// The c=='f' line is there to designate which set of calculations to run, so, that needs to be the //foremost variable to be checked at the beginning of the program.
{
if (c == 'p')
{
pC = atof(optarg);
}
if (c == 'a')
{
pA = atof(optarg);
}
if (c == 'y')
{
pY = atof(optarg);
}
if (c == 't')
{
T = atof(optarg);
}
if (c == 'i')
{
I = atof(optarg);
}
cout << "pC " << pC << endl;
cout << "pC " << pA << endl;
cout << "pY " << pY << endl;
cout << "T " << T << endl;
cout << "I " << I << endl;
//Calculations
cC = ((pC / pA) - 0 / 30) * 5;
cY = ((pY / pA) - 3) * 0.25;
cT = ((T / pA) * 20);
cI = ((2.375) - (I / pA) * 25);
if (cC <= 0)
{
cC = 0;
}
if (cC >= 2.375)
{
cC = 2.375;
}
if (cY <= 0)
{
cY = 0;
}
if (cY >= 2.375)
{
cY = 2.375;
}
if (cT <= 0)
{
cT = 0;
}
if (cT >= 2.375)
{
cT = 2.375;
}
if (cI <= 0)
{
cI = 0;
}
if (cI >= 2.375)
{
cI = 2.375;
}
PasserRating = (((cC + cY + cT + cI) / 6) * 100);
string strPR = "Poor";
if (PasserRating <= 85)
{
strPR = "poor";
}
if (PasserRating > 85)
{
strPR = "mediocre";
}
if (PasserRating > 90)
{
strPR = "good ";
}
if (PasserRating > 95)
{
strPR = "great ";
}
cout << strPR << " " << PasserRating << endl;
}
if (c == 'c')
{
if (c == 'm')
{
mass = atof(optarg);
}
if (c == 'b')
{
bMass = atof(optarg);
}
if (c == 'd')
{
dist = atof(optarg);
}
if (c == 'v')
{
velo = atof(optarg);
}
timeTravel = (dist * 1000) / velo;
cout << "time:" << timeTravel << endl;
cout << "mass " << mass << endl;
cout << "bMass " << bMass << endl;
cout << "dist " << dist << endl;
cout << "velo " << velo << endl;
for (x = 0; x < (10); x ++)
{
CFdraft = r;
Pair = k * CFdraft * (pow(velo, 3));
Proll = Cr * g * (mass + bMass) * velo;
Psec = Pair + Proll;
Et = (Psec * timeTravel);
E = E + Et;
Eavg = E / timeTravel;
}
cout << Eavg << " KJ" << endl;
}
}
return 0;
}

I seriously recommend properly indenting your code. If you did, you would see this:
if(c == 'f'){
if (c == 'p')
...
}
Clearly c is not going to be equal to 'f' and 'p' at the same time.

You never execute your parsing code - everything is inside if(c == 'f') condition, which is obviously true only for the first time you run the loop... So you just get random values from the memory.

Related

Renaming filenames in two directories IF certain characters between them match - vector subscript out of range

My first job as an intern was to write a program to compare certain characters in the filenames of two different directories, and if they match, rename them. I wrote a custom code to match the characters. The initial few files get renamed in both directories, but it breaks after a point, giving a vector subscript out of range error.
I have an idea of how to fix such a vector range error from all the other posts, but nothing seemed to work. Any input would be appreciated!
PS: I am not a coder and this is my third official program. I understand the code is a bit messy.
Here is the code:
#include<dirent.h>
#include<vector>
#include<sstream>
int main()
{
cout << "Comparer - Renamer v.0.1.beta\n\n";
string dr1, dr2;
int x, y;
DIR *d1;
struct dirent *dir1;
vector<string> a;
a.reserve(25000);
int i = 0;
cout << "Enter the first directory (format : log_2017...) : ";
cin >> dr1;
d1 = opendir(dr1.c_str());
if (d1){
while ((dir1 = readdir(d1)) != NULL){
i++;
a.push_back(dir1->d_name);
}
closedir(d1);
}
x = a.size();
cout << "\nEnter the second directory (format : 2017.12...) : ";
cin >> dr2;
DIR *d2;
struct dirent *dir2;
vector<string> b;
b.reserve(25000);
int j = 0;
d2 = opendir(dr2.c_str());
if (d2){
while ((dir2 = readdir(d2)) != NULL){
j++;
b.push_back(dir2->d_name);
}
closedir(d2);
}
y = b.size();
ostringstream osa, nsa, osb, nsb;
string oldname_a, newname_a, oldname_b, newname_b;
int u, v, w;
for (int l = 2; l < x; l++){
for (int k = l; k < y; k++){
int c = a[l][20] * 10 + a[l][21];
int d = b[k][14] * 10 + b[k][15];
int e = a[l][17] * 10 + a[l][18];
int f = b[k][11] * 10 + b[k][12];
if (a[l][4] == b[k][0] && a[l][5] == b[k][1] && a[l][6] == b[k][2] && a[l][7] == b[k][3] && a[l][9] == b[k][5] && a[l][10] == b[k][6] && a[l][12] == b[k][8] && a[l][13] == b[k][9]){
u = 0;
}
else{
u = 1;
}
if ((e - f) == 0 && abs(c - d) < 12){
v = 0;
}
else{
v = 1;
}
if ((e - f) == 1 && ((c == 58) || (c == 59) || (c == 0) || (c == 1) || (c == 2))){
w = 0;
}
else{
w = 1;
}
if (u == 0 && (v == 0 || w == 0)){
osa.str(string());
osa << dr1 << "\\" << a[l];
nsa.str(string());
nsa << dr1 << "\\" << l - 1 << ". " << a[l];
oldname_a = osa.str();
newname_a = nsa.str();
osb.str(string());
osb << dr2 << "\\" << b[k];
nsb.str(string());
nsb << dr2 << "\\" << l - 1 << ". " << b[k];
oldname_b = osb.str();
newname_b = nsb.str();
rename(oldname_a.c_str(), newname_a.c_str())
rename(oldname_b.c_str(), newname_b.c_str())
break;
}
}
}
return 0;
}
Presently the code is set such that it shows me how the comparison between the filenames is made.
It turns out I was not debugging properly, and the problem was in this part of the code:
int c = a[l][20] * 10 + a[l][21];
int d = b[k][14] * 10 + b[k][15];
int e = a[l][17] * 10 + a[l][18];
int f = b[k][11] * 10 + b[k][12];
I did not know that I couldn't assign an integer from a string/char directly to an int. I converted the char to int (which would give me the ASCII value of the char) and then subtracted it by 48 to convert it to decimal (I do not know if there is an easier way to do this, but this seemed to have worked for me!) The modified part looks like this:
c = ((int)a[l][20] - 48) * 10 + ((int)a[l][21] - 48);
d = ((int)b[k][14] - 48) * 10 + ((int)b[k][15] - 48);
e = ((int)a[l][17] - 48) * 10 + ((int)a[l][18] - 48):
f = ((int)b[k][11] - 48) * 10 + ((int)b[k][12] - 48);
There was also a small manual error in the conditions, which I also rectified.

Exit a while loop with one specific key stroke in C++

I am trying to exit a while loop with this one specific character key input |.
The only way I figured out how is to transform the int user input in char. For some reason, when I input the | character when the program is running, I only receive: Press any key to continue.... My final goal (as I hope is visible from my code) is for the program to actually list all inputs in my vector and then terminate.
I am new to C++ and very lost on this point. If anyone could point me in the right direction I will be very appreciative.
I am running a Windows 8 Entreprise machine.
About the program
This is a simple program that takes user input of integers, adds them to a vector and compares the last two to see which one is bigger, smaller etc.
Full code is here
#include "../../std_lib_facilities.h"
// conversion of units to meters
double funconvert(double x, string unit)
{
const double cm_m = 1.0 / 100.0, in_cm = 2.54, ft_in = 12;
if (unit == "m")
return x;
else if (unit == "cm")
return x = x * cm_m;
else if (unit == "in")
return x = x * in_cm * cm_m;
else if (unit == "ft")
return x = x * ft_in * in_cm * cm_m;
else
cout << "Unknown unit value.\n";
}
// printing the large and the small variables
void printresult(double smallest, double largest)
{
cout << "the smaller value is: " << smallest << "\n";
cout << "the larger value is: " << largest << "\n";
}
int main()
{
vector<double>numbers;
double a, b, smallest, largest;
char the_stop;
string unit;
cout << "Please enter an intiger followed by a measurment unit [e.g 10cm]:";
// Take input
while (cin >> a)
{
char the_stop = a;
cin >> unit;
cout << the_stop;
// check if this is the first number entered
if (numbers.size() == 0)
{
a = funconvert(a, unit);
b = a;
numbers.push_back(a);
numbers.push_back(b);
}
else if (the_stop == '|')
{
// This is not working for some reason... ERROR
sort(numbers);
for (int i = 0; i < numbers.size(); ++i)
cout << numbers[i];
break;
}
else
{
//assign a and b to the last two numbers in a vector
a = funconvert(a, unit);
numbers.push_back(a);
a = numbers[(numbers.size() - 1)];
b = numbers[(numbers.size() - 2)];
// numbers.erase(numbers.begin()); // enable if desire to keep the vector empty
}
// find out which variable is larger and smaller
if (a > b && (a/b-1) >= 0.01)
{
smallest = b;
largest = a;
printresult(smallest, largest);
}
else if (a < b && (b / a - 1) >= 0.01)
{
smallest = a;
largest = b;
printresult(smallest, largest);
}
else if ((a / b - 1) < 0.01 && (a / b - 1) != 0.00 || (b / a - 1) < 0.01 && (a / b - 1) != 0.00)
{
cout << "the nubers are almost equal\n";
}
else
cout << a << " equals " << b << "\n";
}
return 0;
}
Code UPDATED
#include "../../std_lib_facilities.h"
// conversion of units to meters
double funconvert(double x, string unit)
{
const double cm_m = 1.0 / 100.0, in_cm = 2.54, ft_in = 12;
if (unit == "m")
return x;
else if (unit == "cm")
return x = x * cm_m;
else if (unit == "in")
return x = x * in_cm * cm_m;
else if (unit == "ft")
return x = x * ft_in * in_cm * cm_m;
else
cout << "Unknown unit value.\n";
}
// printing the large and the small variables
void printresult(double smallest, double largest)
{
cout << "the smaller value is: " << smallest << "\n";
cout << "the larger value is: " << largest << "\n";
}
int main()
{
vector<double>numbers;
double a, b, smallest, largest;
char the_stop;
string unit;
cout << "Please enter an intiger:";
// Take input
while (cin >> a)
{
// check if the | character is pressed
char the_stop = a;
if (the_stop == '|')
{
cout << "start";
sort(numbers);
for (int i = 0; i < numbers.size(); ++i)
cout << numbers[i];
}
else
{
cout << "And now the unit value:";
cin >> unit;
}
// check if this is the first number entered
if (numbers.size() == 0)
{
a = funconvert(a, unit);
b = a;
numbers.push_back(a);
numbers.push_back(b);
}
else
{
//assign a and b to the last two numbers in a vector
a = funconvert(a, unit);
numbers.push_back(a);
a = numbers[(numbers.size() - 1)];
b = numbers[(numbers.size() - 2)];
// numbers.erase(numbers.begin()); // enable if desire to keep the vector empty
}
// find out which variable is larger and smaller
if (a > b && (a/b-1) >= 0.01)
{
smallest = b;
largest = a;
printresult(smallest, largest);
}
else if (a < b && (b / a - 1) >= 0.01)
{
smallest = a;
largest = b;
printresult(smallest, largest);
}
else if ((a / b - 1) < 0.01 && (a / b - 1) != 0.00 || (b / a - 1) < 0.01 && (a / b - 1) != 0.00)
{
cout << "the nubers are almost equal\n";
}
else
cout << a << " equals " << b << "\n";
}
return 0;
}

Error on program opening

When I try to start my C++ program it stops with error "5.exe has stopped working". This program supposed to calculate how many tiles you need for pool, if number of tiles on one side is non-round number, add one row of tiles to it. P.S. Sorry for my bad English.
#include <iostream>
#include <math.h>
#include <cstdlib>
using namespace std;
int main()
{
int x,y,z;
int a,b;
cout << "Insert dimensions of pool in metres: " << endl;
cin >> x >> y >> z;
cout << "Insert dimensions of tile in centimeters: " << endl;
cin >> a >> b;
a=a/100;
b=b/100;
int brx = 0, brzx = 0, bry = 0, brzy = 0, bxpod = 0, bypod = 0;
if (x%a == 0) {
brx = x / a;
}
else {
brx = x / a + 1;
}
if (z%b == 0) {
brzx = z / b;
}
else {
brzx = z / b + 1;
}
if (y%a == 0) {
bry = y / a;
}
else {
bry = y / a + 1;
}
if (z%b == 0) {
brzy = z / b;
}
else {
brzy = z / b + 1;
}
if (x%a == 0) {
bxpod = x / a;
}
else {
bxpod = x / a + 1;
}
if (y%b == 0) {
bypod = y / b;
}
else {
bypod = y / b + 1;
}
int s = (brx*brzx + bry*brzy) * 2 + bxpod*bypod;
cout << "You need " << s << "tiles." << endl;
system("pause");
return 0;
}
Using a debugger, you can easily find that you have a division by 0 in the following lline:
if (x%a == 0) {
brx = x / a;
}
You are doing an integer division on "a":
a = a / 100;
So if a is lower than 100, a will be 0. 10 / 100 = 0.1 = 0 when cast as int.
You should use double instead of int

Why does a mt19937 generator, generate the same result everytime when used in a while loop

I've been writing this game to just type in the amount of humans and skeletons with a random attack chance. If you enter in the same amount when running the program over and over it generates the same amount. Why isn't the hitChance/random attack amount changing everytime the while loop restarts? When I print the attackChance(randGen) in the while loop it changes. Why isn't the randGen changing the output of the winner of the battle?
#include <iostream>
#include <string>
#include <random>
#include <ctime>
using namespace std;
int getNumSkeletons();
int getNumHumans();
void finishedBattleStats(int numHumans, int startHumans, int numSkeletons, int startSkeletons);
void simulatedBattle(int &numSkeletons, int &numHumans, int &startHumans, int &startSkeletons);
int main() {
int startHumans;
int startSkeletons;
int numHumans;
int numSkeletons;
cout << "------------------------------------\nSkeletons V Humans\n\n";
//Gets Number of Humans
numHumans = getNumHumans();
startHumans = numHumans;
//Gets Number of Skeletons
numSkeletons = getNumHumans();
startSkeletons = numSkeletons;
//Simulates Battle
simulatedBattle(numSkeletons, numHumans, startHumans, startSkeletons);
//End Battle Stats
finishedBattleStats(numHumans, startHumans, numSkeletons, startSkeletons);
cin.get();
return 0;
}
int getNumHumans() {
int numHumans;
cout << "Enter number of Humans: \n";
cin >> numHumans;
return numHumans;
}
int getNumSkeletons() {
int numSkeletons;
cout << "Enter number of Skeletons: \n";
cin >> numSkeletons;
return numSkeletons;
}
void simulatedBattle(int &numSkeletons, int &numHumans, int &startHumans, int &startSkeletons) {
static mt19937 randGen(time(NULL));
uniform_real_distribution<float> attackChance(0.0f, 1.0f);
//HumanProperties
float humanDamage = 30.0f;
float humanHitChance = 0.6f;
float humanCritChance = 0.2f;
float humanHealth = 50.0f;
float startHumanHealth = humanHealth;
float currentHuman = startHumanHealth;
//Skeleton Properties
float skeletonDamage = 20.0f;
float skeletonHitChance = 0.7f;
float skeletonCritChance = 0.2f;
float skeletonHealth = 40.0f;
float startSkeletonHealth = skeletonHealth;
float currentSkeleton = startSkeletonHealth;
char turn = 'H';
float hitChance;
while (numSkeletons > 0 && numHumans > 0) {
hitChance = attackChance(randGen);
if (turn == 'H') {
if (hitChance > humanHitChance) {
currentSkeleton -= humanDamage;
turn = 'S';
if (currentSkeleton < 0) {
numHumans--;
currentSkeleton = startSkeletonHealth;
turn = 'S';
}
}
}
else {
if (hitChance > skeletonHitChance) {
currentHuman -= skeletonDamage;
turn = 'H';
}
if (currentHuman < 0) {
numSkeletons--;
currentHuman = startHumanHealth;
turn = 'H';
}
}
}
}
void finishedBattleStats(int numHumans, int startHumans, int numSkeletons, int startSkeletons) {
if (numHumans == 0) {
cout << "Skeletons won! \n\n";
cout << "Skeletons left: " << numSkeletons << endl;
cout << "Skeleton Casualties: " << startSkeletons - numSkeletons << endl;
cout << "All " << startHumans << " humans are dead! \n\n";
cout << "Game Over!";
cin.get();
}
else {
cout << "Humans Won! \n\n";
cout << "Humans left: " << numHumans << endl;
cout << "Human Casualties: " << startHumans - numHumans << endl;
cout << "All " << startSkeletons << " skeletons are dead! \n\n";
cout << "Game Over!";
cin.get();
}
}
IMHO opinion you have a flaw in the battle calculations. That is, when a human's healths goes < 0 you subtract a skeleton and not a human and vice versa. Below is the correction. With a demo. I tried the demo a number of times and gives different results (ENJOY):
void simulatedBattle(int &numSkeletons, int &numHumans, int &startHumans, int &startSkeletons) {
uniform_real_distribution<float> attackChance(0.0f, 1.0f);
static mt19937 randGen(time(NULL));
//HumanProperties
float humanDamage = 25.0f;
float humanHitChance = 0.2f;
float humanCritChance = 0.2f;
float humanHealth = 50.0f;
float startHumanHealth = humanHealth;
float currentHuman = startHumanHealth;
//Skeleton Properties
float skeletonDamage = 20.0f;
float skeletonHitChance = 0.8f;
float skeletonCritChance = 0.2f;
float skeletonHealth = 40.0f;
float startSkeletonHealth = skeletonHealth;
float currentSkeleton = startSkeletonHealth;
char turn = 'H';
float hitChance;
while (numSkeletons > 0 && numHumans > 0) {
hitChance = attackChance(randGen);
if (turn == 'H') {
if (hitChance > humanHitChance) {
currentSkeleton -= humanDamage;
if (currentSkeleton < 0) {
--numSkeletons;
currentSkeleton = startSkeletonHealth;
}
turn = 'S';
}
}
else {
if (hitChance > skeletonHitChance) currentHuman -= skeletonDamage;
if (currentHuman < 0) {
--numHumans;
currentHuman = startHumanHealth;
}
turn = 'H';
}
}
}
LIVE DEMO
You have to seed a mersenne twister before use, or you'll always have the same output.
It is common practice to seed it with the internal clock:
// obtain a seed from the timer
myclock::duration d = myclock::now() - beginning;
unsigned seed2 = d.count();
generator.seed (seed2);
ref: std::mersenne_twister_engine::seed

can I create a window in c++ using existing project code

I was wondering if i could create a window using my existing project code. This is a school project. However, I have completed the actual coding part and just wanted to make the project fancier, so to say. Thank you so much in advance for all the support.
Here is the actual code in case it would be of any help. It's a bit lengthy so be warned :) Once again, thank you in advance
#define NOMINMAX
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <windows.h>
#include <Windows.h>
#include <chrono>
#include <string>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int key[3][3];
double inverted[3][3];
int store[1][3] = { 0 };
int conv[666];
int random1()
{
unsigned long long int xRan;
srand(time(NULL));
xRan = rand() % 9999 + 1;
return xRan;
}
int random2()
{
unsigned long long int xRan;
xRan = rand() % 9999 + 1;
return xRan;
}
int random3()
{
int xRan;
xRan = rand() % 9999 + 1;
return xRan;
}
void clear_screen(char fill = ' ') {
COORD tl = { 0, 0 };
CONSOLE_SCREEN_BUFFER_INFO s;
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(console, &s);
DWORD written, cells = s.dwSize.X * s.dwSize.Y;
FillConsoleOutputCharacter(console, fill, cells, tl, &written);
FillConsoleOutputAttribute(console, s.wAttributes, cells, tl, &written);
SetConsoleCursorPosition(console, tl);
}
int convert(char letter) {
int conv;
conv = (int)letter;
return conv;
}
void reverseMult(double inv[3][3], int decode[1][3])
{
store[0][0] = decode[0][0] * inv[0][0] + decode[0][1] * inv[1][0] + decode[0][2] * inv[2][0] + 0.5;
store[0][1] = decode[0][0] * inv[0][1] + decode[0][1] * inv[1][1] + decode[0][2] * inv[2][1] + 0.5;
store[0][2] = decode[0][0] * inv[0][2] + decode[0][1] * inv[1][2] + decode[0][2] * inv[2][2] + 0.5;
}
void matrixMult(int q, int w, int e, int a[3][3])
{
int A[1][3] = { q, w, e };
int B[3][3] = {
{ a[0][0], a[0][1], a[0][2] },
{ a[1][0], a[1][1], a[1][2] },
{ a[2][0], a[2][1], a[2][2] }
};
store[0][0] = A[0][0] * B[0][0] + A[0][1] * B[1][0] + A[0][2] * B[2][0];
store[0][1] = A[0][0] * B[0][1] + A[0][1] * B[1][1] + A[0][2] * B[2][1];
store[0][2] = A[0][0] * B[0][2] + A[0][1] * B[1][2] + A[0][2] * B[2][2];
//cout << store[0][0] << endl << store[0][1] << endl << store[0][2] << endl << endl;
}
char reverseConv(int x){
char conv;
conv = (char)x;
return conv;
}
void inverse(int key[3][3], double det){
int cofactor[3][3] = {
{ (key[1][1] * key[2][2] - key[1][2] * key[2][1]), -(key[1][0] * key[2][2] - key[1][2] * key[2][0]), (key[1][0] * key[2][1] - key[1][1] * key[2][0]) },
{ -(key[0][1] * key[2][2] - key[0][2] * key[2][1]), (key[0][0] * key[2][2] - key[0][2] * key[2][0]), -(key[0][0] * key[2][1] - key[0][1] * key[2][0]) },
{ (key[0][1] * key[1][2] - key[0][2] * key[1][1]), -(key[0][0] * key[1][2] - key[0][2] * key[1][0]), (key[0][0] * key[1][1] - key[0][1] * key[1][0]) }
};
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
inverted[i][j] =det * cofactor[i][j];
}
}
}
int main()
{
while (1){
cout << "Would you like to encrypt or decrypt?(e/d)\n " << endl;
string ende;
cin >> ende;
clear_screen();
if (ende == "e")
{
cout << "Please enter a name for the message: " << endl << endl;
string file;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
getline(cin, file);
clear_screen();
file += ".txt";
ofstream encrypt;
encrypt.open(file);
string message;
cout << "Please enter the message you would like to encrypt: " << endl << endl;
//cin.ignore(numeric_limits<streamsize>::max(), '\n'); --- Not needed anymore, uncomment if you cannot input message
getline(cin, message);
if (message.length() % 3 != 0)
message += ' ';
if (message.length() % 3 != 0)
message += ' ';
clear_screen();
for (int i = 0; i < message.length(); ++i)
{
conv[i] = convert(message[i]);
}
int det = 0;
while (1){
key[0][0] = random1(); //1
key[0][1] = random2(); //2
key[0][2] = random3(); //3
key[1][0] = random1() * 13 / 7; //4
key[1][1] = random2() * 23 / 7; //5
key[1][2] = random3() * 33 / 7; //6
key[2][0] = random1() * 18 / 15; //7
key[2][1] = random2() * 18 / 12; //8
key[2][2] = random3() * 18 / 10; //9
det = key[0][0] * key[1][1] * key[2][2] + key[0][1] * key[1][2] * key[2][0] + key[0][2] * key[1][0] * key[2][1]
- key[0][2] * key[1][1] * key[2][0] - key[0][0] * key[1][2] * key[2][1] - key[0][1] * key[1][0] * key[2][2];
if (det != 0)
break;
}
encrypt << key[0][0] << ' ' << key[0][1] << ' ' << key[0][2] << ' '
<< key[1][0] << ' ' << key[1][1] << ' ' << key[1][2] << ' '
<< key[2][0] << ' ' << key[2][1] << ' ' << key[2][2] << endl << endl;
int a, b, c;
int count = 0;
for (int i = 0; i < (message.length)() / 3; ++i)
{
int counting = 0;
a = conv[count];
count++;
b = conv[count];
count++;
c = conv[count];
count++;
matrixMult(a, b, c, key);
encrypt << store[0][counting] << ' ';
counting++;
encrypt << store[0][counting] << ' ';
counting++;
encrypt << store[0][counting] << endl;
}
encrypt.close();
Sleep(750);
cout << "Your message has been encrypted." << endl;
Sleep(750);
cout << "Please check " << file << " for the encrypted message and key" << endl << endl;
Sleep(750);
}
if (ende == "d")
{
cout << "Please enter the name of the file you would like to decrypt: " << endl << endl;
string file;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
getline(cin, file);
clear_screen();
file += ".txt";
ifstream decrypt;
decrypt.open(file);
int key[3][3];
for (int i = 0; i < 3; ++i)
{
for (int k = 0; k < 3; ++k){
decrypt >> key[k][i];
}
}
int det = 0;
det = key[0][0] * key[1][1] * key[2][2] + key[0][1] * key[1][2] * key[2][0] + key[0][2] * key[1][0] * key[2][1] - key[0][2] * key[1][1] * key[2][0] - key[0][0] * key[1][2] * key[2][1] - key[0][1] * key[1][0] * key[2][2];
double detInv = 1;
detInv /= det;
//double inv;
inverse(key, detInv);
int out[1][3];
int count = 0;
while (!decrypt.eof()){
for (int i = 0; i < 3; ++i)
{
decrypt >> out[0][i];
}
reverseMult(inverted, out);
count++;
char a, b, c;
a = reverseConv(store[0][0]);
b = reverseConv(store[0][1]);
c = reverseConv(store[0][2]);
if (decrypt.eof())
break;
cout << a << b << c;
}
}
cout << endl << endl;
cout << "Would you like to continue?(y/n) ";
char again;
cin >> again;
if (again != 'y')
exit(0);
clear_screen();
}
return 0;
}
Yes, you can convert your project to a Windowing application. You have two choices:
Use Windows (native) API
Use graphics framework
Windows API
The Windows API is the direct method for creating windows. However, it is a lot of code, lots of chances for defects to be injected. It is a good learning experience about how the Windowing system works. Get Petzold's book.
GUI Framework
There are a lot of GUI frameworks out there. These C++ frameworks have simplified the GUI and Widget creation, using object oriented programming. There are many out there, so search the internet for "GUI Framework C++ review".
A Different Programming Perspective
In your present project, the OS executes the program and statements are executed in order. A windowing system is based on event driven programming. In summary, your GUI is waiting for an event to occur.
A simple example for your project is a window with a single button. When the User clicks on the button, the Windowing system sends a message to the button event handler. The event handler is a function that will execute your code.
As Thomas said, yes you can migrate your code to a Windows application, by either going native with Win32 or by either using a C++ GUI Framework (QT, wxWindows, ...).
However, you will need to invest time to learn one of the solution. I would suggest to learn a C++ Framework, programming with low-level Win32 api is not very used today.
Although it's off-topic, I would suggest some improvements to your code.
First, you shouldn't use goto, and replace them by a while. You can replace
again:
xRan = rand() % 9999 + 1;
if (xRan <1)
goto again;
By
do{
xRan = rand() % 9999 + 1;
} while (xRan < 1);
Note that in this case, a goto or a while is useless as xRan will always be superior or equal to 1 (rand() always returns a positive value)
Also you can replace convert and reverseConv very long functions by a constant array of struct values (struct contains a int and a const char*). convert and reverseConvert functions would only parse the array to find a proper match.