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;
}

C++ Primer Plus Chapter 6 Exercise 8

c++IconWe create a simple file reading program in exercise 8. As usual, there where a couple of ways to accomplish this. I chose to declare my input file, and as long as we did not receive and error opening the file or reach end of file, use isprint to count any characters in the file. Mind you “file.txt” is to be placed in the same directory as your program with some characters in it. See my source below:

8. Write a program that opens a text file, reads it character-by-character to the end of the file, and reports the number of characters in the file.

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

using namespace std;

int main()
{
ifstream inFile;
inFile.open("file.txt");

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

char letter;
int count = 0;
inFile >> letter;
while (!inFile.eof())
{
if (isprint(letter))
count++;
inFile >> letter;
}

cout << "\n" << "Number of characters is: " << count << endl;

// Check for EOF
if (inFile.eof())
cout << "End of file found.\n";
else if (inFile.fail())
cout << "Data mismatch.\n";
else
cout << "Input terminated for unknown reason.\n";

// Clean
inFile.close();

cin.get();

return 0;
}

C++ Primer Plus Chapter 6 Exercise 7

c plus plusThere are a number of ways to do exercise 7. My approach uses the switch statement suggestion to keep tabs of vowels. Also, it analyses one word at a time except you have to press enter after each word for it to tally it appropriately. As mentioned, this could be completed multiple ways. Take a look at my solution below:

7.Write a program that reads input a word at a time until a lone q is entered. The program
should then report the number of words that began with vowels, the number that began
with consonants, and the number that fit neither of those categories. One approach is to
use isalpha() to discriminate between words beginning with letters and those that
don’t and then use an if or switch statement to further identify those passing the
isalpha() test that begin with vowels. A sample run might look like this:
Enter words (q to quit):
The 12 awesome oxen ambled
quietly across 15 meters of lawn. q
5 words beginning with vowels
4 words beginning with consonants
2 others

#include <iostream>
#include <string>

using namespace std;

const int size = 50;

int main()
{
char word[size];
int vowels = 0;
int consonants = 0;
int others = 0;

cout << "Enter words (q to quit): ";

while(cin.get(word, size) && (word[0] != 'q' || word[0] != 'Q'))
{
char * ch = new char;
*ch = word[0];

if(isalpha(word[0]))
{
switch(*ch)
{
case 'a' : vowels++;
break;
case 'e' : vowels++;
break;
case 'i' : vowels++;
break;
case 'o' : vowels++;
break;
case 'u' : vowels++;
break;
default  : consonants++;
break;
}
}
else
others++;
cin.get(); // keep grabbing words after enter is pressed
delete ch;
}
cout << vowels << " words beginning with vowels\n"
<< consonants << " words begining with consonants\n"
<< others << " others";

return 0;
}

C++ Primer Plus Chapter 6 Exercise 6

c plus plusExercise 6 has us working with more structs. This time we create a dynamically allocated array of structures. This sounds interesting but is not too difficult after you start putting code to compiler. Essentially, you create your array, declare variables that were mentioned int the text, use the “new” keyword to allow numDonors and our struct, then loop through patrons and their amounts. See my source below for a more clear explanation:

6. Put together a program that keeps track of monetary contributions to the Society for the
Preservation of Rightful Influence. It should ask the user to enter the number of contributors
and then solicit the user to enter the name and contribution of each contributor.
The information should be stored in a dynamically allocated array of structures. Each
structure should have two members: a character array (or else a string object) to store
the name and a double member to hold the amount of the contribution. After reading
all the data, the program should display the names and amounts donated for all donors
who contributed $10,000 or more. This list should be headed by the label Grand
Patrons. After that, the program should list the remaining donors. That list should be
headed Patrons. If there are no donors in one of the categories, the program should print
the word “none.” Aside from displaying two categories, the program need do no sorting.

#include <iostream>
#include <string>

using namespace std;

struct contrib{
string name;
double amount;
};

int main()
{
int numDonors = 0;
int patrons = 0;
int grandPatrons = 0;

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

cout << "Enter number of contributors: ";
cin >> numDonors;
cout << "\n";

contrib *society = new contrib[numDonors];

// Gather names and amounts
for(int i = 0; i < numDonors; i++)
{
cout << "Enter the name of the contributor: ";
cin >> society[i].name;
cout << "Enter the contribution anount: ";
cin >> society[i].amount;
}

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";

// free memory
delete [] society;

return 0;
}