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

Two Column HTML and CSS Starter Template

This is quick and dirty little CSS template I like to use when im doing web pages that would fit the two column style. Instead of having to retype code I know I will probably use like header, footer, menu, content, etc. I can just drop this right in my editor. With a little bit of tweaking, I can take this template and create a great looking web site. Take a look at the source:


/* fix white space around edge */
html, body
{
margin: 0;
padding: 0;
height: 100%;
}

#container
{
margin: 0 auto;
width: 100%;
background: #fff;
}

#header
{
background: #ccc;
padding: 20px;
}

#header h1 { margin: 0; }

#navigation
{
float: left;
width: 100%;
background: #333;
}

#navigation ul
{
margin: 0;
padding: 0;
}

#navigation ul li
{
list-style-type: none;
display: inline;
}

#navigation li a
{
display: block;
float: left;
padding: 5px 10px;
color: #fff;
text-decoration: none;
border-right: 1px solid #fff;
}

#navigation li a:hover { background: #383; }

#content-container
{
float: left;
width: 100%;
background: #FFF /*url(layout-two-liquid-background.gif) repeat-y 68% 0 */;
}

#content
{
clear: left;
float: left;
width: 60%;
padding: 20px 0;
margin: 0 0 0 4%;
display: inline;
}

#content h2 { margin: 0; }

#right
{
float: right;
width: 26%;
padding: 20px 0;
margin: 0 3% 0 0;
display: inline;
}

#right h3 { margin: 0; }

#footer
{
clear: left;
background: #ccc;
text-align: right;
padding: 20px;
height: 1%;
}
<pre>

And the associated html:

<link rel="stylesheet" type="text/css" href="test.css" />
<div id="container">
<div id="header">
<h1>
Site name
</h1>
</div>
<div id="navigation">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact us</a></li>
</ul>
</div>
<div id="content-container">
<div id="content">
<h2>
Page heading
</h2>
<p>
Lorem ipsum dolor sit amet consect etuer adipi scing elit sed diam nonummy nibh euismod tinunt ut laoreet dolore magna aliquam erat volut. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi.
</p>
<p>
Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
</p>
<p>
Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.
</p>
</div>
<div id="aside">
<h3>
Right
</h3>
<p>
Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan.
</p>
</div>
<div id="footer">
Copyright © Site name, 20XX
</div>
</div>
</div>

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