C Program To Determine Byte Order (Endianness)

C programRecently I needed to needed to check the endianness of a machine. I assumed the machine was Little Indian but wanted to make sure, thus this C code snippet. It’s important to understand that endian.h is not cross-platform, and exist only on Linux machines. There are standard byte order functions you can use if you are on Windows to figure this stuff out. Perhaps I will show an example of that later.

ByteOrder.c


#include <stdio.h>
#include <endian.h>

int main (void)
{
#if BYTE_ORDER == LITTLE_ENDIAN
printf("system is little Endian \n");
#elif BYTE_ORDER == BIG_ENDIAN
printf("system is big Endian \n");
#else
printf("whats going on? \n");
#endif

return 0;
}

C++ Class Example Building Monsters

c plus plusThis is a simple example of class inheritance in C++.  The class could certainly be built upon to make something like a console based RPG, but in this example we are  just showing an example of a class in C++.  Yes, I actually am working on a small RPG for the console, which I will eventually post. For now, we will create a few monsters with this quick and dirty show of inheritance and encapsulation. If you’ve been waiting on solutions to more wargames for OverTheWire, don’t worry, I do have them and will be throwing those up here soon. Cheers.

#include <iostream>
#include <string>

using namespace std;

//ENCAPSULATION = combine what an object is with what it does
/*-------------------------------------------------------------------------------*/
class Monster
{
public:
//Constructor
Monster() {cout << "\n\tBuilding a Monster...";}
//Destructor
~Monster() {cout << "\n\tDestroying a Monster...";}

//Member Methods
void Rampage() {cout << "\n\tMonster rampagign through the city!";}

void DisplayStats()
{
cout << "\n\n\t-------Monster Stats--------";
cout << "\n\tName: " << MonsterName;
cout << "\n\tLife: " << LIFE;
cout << "\n\tSize: " << SIZE;
cout << "\n\tWeight: "  << WEIGHT;
cout << "\n\t----------------------------";

}

//Accessor Methods
int GetLife() {return LIFE;}
void SetLife(int x) {LIFE = x;}
double GetSize() {return SIZE;}
void SetSize(int x) {SIZE = x;}
double GetWeight() {return WEIGHT;}
void SetWeight(double x) {WEIGHT = x;}
string GetMonsterName() {return MonsterName;}
void SetMonsterName(string x) {MonsterName = x;}

private:
int LIFE;
double SIZE;
double WEIGHT;
string MonsterName;
};

/*-------------------------------------------------------------------------------*/

class Dragon : public Monster
{
public:
Dragon() {cout << "\n\tBuilding a dragon";}
~Dragon() {cout << "\n\tDestroying a Dragon";}

void BreathFire() {cout << "\n\tDragon breathing fire\n";}
};

/*-------------------------------------------------------------------------------*/

class Unicorn : public Monster
{
public:
Unicorn() {cout << "\n\tBuilding a Unicorn";}
~Unicorn() {cout << "\n\tDestroying a Unicorn";}

void Fly() {cout << "\n\tUnicorn flying\n";}
};

/*-------------------------------------------------------------------------------*/

int main()
{
//stack
Dragon * Bill = new Dragon();
Unicorn * Sue = new Unicorn();

Bill->SetMonsterName("Bill");
Bill->SetLife(500);
Bill->SetSize(50);
Bill->SetWeight(4);
Bill->DisplayStats();
Bill->BreathFire();

Sue->SetMonsterName("Sue");
Sue->SetLife(350);
Sue->SetSize(25);
Sue->SetWeight(2);
Sue->DisplayStats();
Sue->Fly();

cout << "\n\n\t";

return 0;
}

C++ Primer Plus Chapter 7 Exercise 3

c plus plusAfter a bit of a break, I am ready to continue these exercises as well as put out some other things I have been working on.  Chapter 7 exercise 3 wants us to create two functions using a structs given values, then use those functions and the struct in a program. Here is my solution to this problem:

3. Here is a structure declaration:
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
a. Write a function that passes a box structure by value and that displays the value of
each member.
b. Write a function that passes the address of a box structure and that sets the volume
member to the product of the other three dimensions.
c. Write a simple program that uses these two functions.

 #include <iostream>

using namespace std;

struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};

void showValue(box);
void setVolume(box*);

int main()
{
box toyBox = {"Elf", 2.5, 3.3, 5.0, 0};
showValue(toyBox);
setVolume(&toyBox);
cout << "\n\nWith volume calculated: \n";
showValue(toyBox);

return 0;
}

void showValue(box ourStruct)
{
cout << "Struct details\n";
cout << "Struct maker: " << ourStruct.maker << endl;
cout << "Struct height: " << ourStruct.height << endl;
cout << "Struct width: " << ourStruct.width << endl;
cout << "Struct length: " << ourStruct.length << endl;
cout << "Struct volume: " << ourStruct.volume << endl;
}

void setVolume(box* ourStruct)
{
ourStruct->volume = ourStruct->height * ourStruct->width * ourStruct->length;
}
 

C++ Primer Plus Chapter 7 Exercise 2

c plus plusExercise 2 is a good lesson in functions. You will be forced to use a function for every requirement of the program. In addition, you will have to be inventive with how you terminate the program early and still calculate a running average. See my source below:
2. Write a program that asks the user to enter up to 10 golf scores, which are to be stored
in an array. You should provide a means for the user to terminate input prior to entering
10 scores. The program should display all the scores on one line and report the average
score. Handle input, display, and the average calculation with three separate array-
processing functions.

#include <iostream>

const int maxSize = 10;

// Prototypes
int input(int scores[], int arSize);
double avg(int scores[], int arSize);
void display(int scores[], int arSize);

int main()
{
int scores[maxSize];
int arSize = input(scores, maxSize);
display(scores, arSize);
std::cout << "Average score: " << avg(scores, arSize);
return 0;
}

int input(int scores[], int arSize)
{
double score;
int count = 0;
std::cout << "Enter up to " << maxSize << " scores (press -1 to terminate)\n"; // Loop up to 10 times
for(int i = 0; i < maxSize; i++) // Loop until maxSize
{
std::cout << "Enter Score #" << (i + 1) << ": ";
std::cin >> score;
if(score > 0)
{
scores[i] = score; // assign score to score[i]
count++;
}
else
break;

}
return count; // return something sice fucntion is not void.

}

double avg(int scores[], int arSize)
{
double total = 0;
for(int i = 0; i < arSize; i++) // Loop as many times as was actually inputted
{
total += scores[i];
}
return total/arSize;
}

void display(int scores[], int arSize)
{
std::cout << "Scores: ";
for(int i = 0; i < arSize; i++) // Loop as many times as was actually inputted
{
std::cout << scores[i] << " "; // Print to one line
}
}

C++ Primer Plus Chapter 7 Exercise 1

c plus plusChapter 7 kicks off with a fairly painless reintroduction into functions. We computer harmonic mean for a number pair. There are probably a few ways to do this, but they should all be very similar. Take in two numbers, store them if you like as I did, check if they are zero’s, and if not compute the harmonic mean by way of a function. Check out my source below:

1. Write a program that repeatedly asks the user to enter pairs of numbers until at least one
of the pair is 0. For each pair, the program should use a function to calculate the har-
monic mean of the numbers. The function should return the answer to main(), which
should report the result. The harmonic mean of the numbers is the inverse of the aver-
age of the inverses and can be calculated as follows:
harmonic mean = 2.0 × x × y / (x + y)

#include <iostream>

using namespace std;

float Hmean(int x, int y);

int main()
{
int myArray[2];

cout << "Please enter pairs of numbers: " << endl;
cin >> myArray[0] >> myArray[1];

if(myArray[0] == 0 || myArray[1] == 0)
{
cout << "You have entered a pair matching zero" << endl;
cout << "Exiting..." << endl;
}
else
{
cout << "The Harmonic mean of " << myArray[0] << " and "
<< myArray[1] << " is " << Hmean(myArray[0],myArray[1]);
}
return 0;
}

float Hmean(int x, int y)
{
float calc = 2.0 * x * y / (x + y);

return calc;
}

Simple Windows Server

In an effort to post something completely different. I’m putting up a quick and dirty Windows-based server I recently created. You may or may not have issues compiling this on various versions of Windows. Keep in mind this server is far from robust. It has pretty much no features as of yet. This really was a lesson for me to learn how to set up sockets on a Windows box. What the code is supposed to do is listen on local port 80 for incoming connections. After that it does nothing. I think in future versions I will have it serve a page or perform some function; we’ll see.

#define WIN32_LEAN_AND_MEAN

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <windows.h>

struct SOCKADDR_IN
{
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};

int main()
{
WSAData wsa;
WORD Version = MAKEWORD(2, 1);

WSAStartup(Version, &wsa);

SOCKET Listen = socket(AF_INET,SOCK_STREAM,NULL);
SOCKET Connect = socket(AF_INET,SOCK_STREAM,NULL);

SOCKADDR_IN Server;

Server.sin_addr.s_addr = inet_addr("127.0.0.1");
Server.sin_family = AF_INET;
Server.sin_port = htons(80);

bind(Listen, (SOCKADDR*)&Server, sizeof(Server));

listen(Listen, 1);

int size = sizeof(Server);

std::cout << "Listening for connection...";

for(;;)
{
if(Connect = accept(Listen, (SOCKADDR*)&Server, &size))
std::cout << "Connection found\n";
break;
}

WSACleanup();
std::cin.get();
return 0;
}

C++ Primer Plus Chapter 6 Exercise 9

c++IconThe end of chapter 9 concludes with a fairly hefty compilation of some things you have learned thus far. You probably could have simply made a program that grabbed text from a file, but im sure you would still want to associate it with a struct like we have already done. The majority of this program will stay the same as exercise 6 except a couple of additions; one being we create a file stream named “inFile”. We then associate it with a hard-coded file “contrib.txt”, that has our struct info. Then, we check for a file opening error, see if the first line is an integer, and begin grabbing data from the file. This time I use the “new” keyword and make use of the atoi() function to make all this happen. Examine my source to see how I worked through this one:

9. Do Programming Exercise 6, but modify it to get information from a file. The first item
in the file should be the number of contributors, and the rest of the file should consist of
pairs of lines, with the first line of each pair being a contributor’s name and the second
line being a contribution. That is, the file should look like this:
4
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Rich Raptor
55000

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

struct contrib
{
string name;
double amount;
};

int main()
{
// Create input stream
ifstream inFile;
inFile.open("contrib.txt");

// faile-safe
if (!inFile.is_open())
{
cout << "Failed to open: " << inFile << endl;
exit(EXIT_FAILURE);
}

int numDonors = 0;
int patrons = 0;
int grandPatrons = 0;
char lineOne;

cout << "Society for the Preservation of Rightful Influence" << "\n\n";
cout << "Reading File...\n";

(inFile >> lineOne).get();
if(!isdigit(lineOne))
{
cout << "Number of donors not found\n";
return 2;
}
else
cout << "The number of donors is: " << lineOne << "\n\n";

numDonors = atoi(&lineOne);

contrib *society = new contrib[numDonors];

// Gather names and amounts
for(int i = 0; i < numDonors; i++)
{
getline(inFile, society[i].name); // getline to grab names
cout << "Donor # " << (i+1) << " " << society[i].name << endl;
(inFile >> society[i].amount).get();
/*inFile >> society[i].amount;*/
cout << "Amount: " << (i+1) << society[i].amount<< endl;
}

cout << "\n";
// Display donors over 10000
cout << "Grand Patrons: \n";
for(int x = 0; x < numDonors; x++)
{
if(society[x].amount >= 10000)
{
cout << society[x].name << " Donated: "
<< "$ " << society[x].amount << "\n";
grandPatrons = 1;
}
}
if(grandPatrons == 0)
cout << "none\n";

cout << "\n";

// Display all other patrons

cout << "Patrons list: \n";
for(int y = 0; y < numDonors; y++)
{
if(society[y].amount < 10000)
{
cout << society[y].name << " Donated: "
<< "$ " << society[y].amount << "\n";
patrons = 1;
}
}
if(patrons == 0)
cout << "none\n";
delete [] society;

if (inFile.eof())
cout << "End of file reached.\n";
else if (inFile.fail())
cout << "Input terminated by data mismatch.\n";

// free memory
inFile.close();

return 0;
}