// Filename: CFIRST.CPP
// Program displays a message on-screen
#include <iostream.h>
void main()
{
cout << "I will be a C++ expert!";
}
=======================
// Filename: CH1.CPP
// Introduces get() and put()
#include <fstream.h>
void main()
{
char in_char; // Holds incoming initial
char first, last; // Holds converted first and last initial
cout << "What is your first name initial? ";
cin.get(in_char); // Waits for first initial
first = in_char;
cin.get(in_char); // Ignores newline
cout << "What is your last name initial? ";
cin.get(in_char); // Waits for last initial
last = in_char;
cin.get(in_char); // Ignores newline
cout << endl << "Here they are: " << endl;
cout.put(first);
cout.put(last);
return;
}
========================
// Filename: CHANGBUG.CPP
// Stores the alphabet in a file, reads two letters from it,
// and changes those letters to x
#include <fstream.h>
void main()
{
fstream fp;
char ch; // Holds A through Z
// Opens in update mode so that you can
// read file after writing to it
fp.open("alph.txt", ios::in | ios::out);
if (!fp)
{
cout << endl << "*** Error opening file ***" << endl;
return;
}
for (ch = 'A'; ch <= 'Z'; ch++)
{ fp << ch; } // Writes letters
fp.seekg(8L, ios::beg); // Skips eight letters, points to I
fp >> ch;
// Changes the I to an x
fp.seekg(-2L, ios::cur);
fp << 'x';
cout << "The first character is " << ch << endl;
fp.seekg(16L, ios::beg); // Skips 16 letters, points to Q
fp >> ch;
cout << "The second character is " << ch << endl;
// Changes the Q to an x
fp.seekg(-2L, ios::cur);
fp << 'x';
fp.close();
}
=======================
// Filename: CHARFUNS.CPP
// Uses character arrays and character pointers
#include <iostream.h>
#include <string.h>
void main()
{
char c;
char * cpt0; // A stand-alone character pointer
char * cpt5 = "abcd"; // Points to 5 bytes
char * cpt12 = "Programming"; // Points to 12 bytes
char ara27[27]; // Points to 27 bytes
char * cpt27 = ara27; // Points to 27 bytes
cpt0 = "cpt0 is pointing to this string";
cout << cpt0; // No problem
cpt0 = "A new string for cpt0"; // Still no problem
cout << endl << cpt0 << endl;
// You couldn't
// strcpy(cpt0, "This is a string for cpt0 that is too long")
// though!
cout << "Please type your name (up to 12 characters): ";
cin.get(cpt12, 12); // Okay because of get() 12-char limit
cout << "You typed " << cpt12 << endl << endl;
// cin.get(cpt5, 12) wouldn't work either because
// all characters after the fifth one would overwrite
// memory not pointed to by cpt5
// Fill the 27-character array
for (c = 'A'; c <= 'Z'; c++)
{ ara27[c - 65] = c; } // ASCII A is equivalent to decimal 65
ara27[26] = '\0';;
strcpy(cpt27, ara27); // Okay because they point to
// the same number of bytes
// strcpy(cpt12, ara27) would NOT be okay
cout << "cpt27 contains: " << cpt27;
return;
}
============================
// Filename: CITYNAME.CPP
// Stores and prints a list of city names
#include <iostream.h>
void main()
{
int ctr;
char * cities[5] = {"San Diego", "Miami", "New York",
"Oklahoma City", "St. Louis"};
// Print the cities
// Anywhere a character array can appear, so can the
// elements from the cities array of pointers
cout << "Here are the stored cities:" << endl;
for (ctr = 0; ctr < 5; ctr++)
{ cout << cities[ctr] << endl; }
cout << endl;
// Change the cities with literals
// These assignments store the address of
// the string literals in the elements
cities[0] = "Tulsa";
cities[1] = "Boston";
cities[2] = "Indianapolis";
cities[3] = "Las Vegas";
cities[4] = "Dallas";
// Print the cities again using pointer notation
cout << endl << "After changing the pointers:" << endl;
for (ctr = 0; ctr < 5; ctr++)
{ cout << *(cities + ctr) << endl ; }
cout << endl;
return;
}
==========================
// Filename: CLASSPGM.CPP
// Demonstrates a complete OOP program with class data
#include <iostream.h>
class Date {
int day;
int month;
int year;
public: // Everything that follows is accessible by main()
void prDate(); // Member functions
void setDay(int d);
void setMonth(int m);
void setYear(int y);
};
void Date::prDate() // :: Tells C++ the owner class
{
cout << "Date: " << day << "/" << month << "/"
<< year << endl;
}
void Date::setDay(int d)
{
day = d;
}
void Date::setMonth(int m)
{
month = m;
}
void Date::setYear(int y)
{
year = y;
}
void main()
{
Date today; // Define a new active class variable
// today.day = 20 is NOT possible!!! You must initialize
// the data can only be initialized through member functions
today.setDay(20); // Initialize the day
today.setMonth(6); // Initialize the month
today.setYear(1994); // Initialize the year
today.prDate(); // Print the date (You couldn't print the
// date's values via the dot operator!)
return;
}
=============================
// Filename: COMAVGE.CPP
// Program to compute the average of three values
#include <iostream.h>
void main()
{
double g1, g2, g3; // Variables to hold student grades
cout << "What grade did the first student get? ";
cin >> g1;
cout << "What grade did the second student get? ";
cin >> g2;
cout << "What grade did the third student get? ";
cin >> g3;
double avg = (g1 + g2 + g3) / 3.0; // Computes average
cout << "The student average is " << avg; // Prints average
return;
}
=========================
// File name: CONDEST.CPP
// Shows construction and destruction
// of objects and simple memory management
//
#include <iostream.h>
#include <string.h>
class Name
{
public:
// Constructor
Name();
// Destructor
~Name();
void SetName(const char * newName);
const char * GetName() const;
private:
char * name;
};
void main()
{
cout << "-- First line of main() --" << endl;
Name firstName;
firstName.SetName("firstName");
Name * secondName = new Name;
secondName->SetName("secondName");
cout << "-- Before block --" << endl;
// New block
{
cout << "-- First line of block --" << endl;
Name thirdName;
Name fourthName;
thirdName.SetName("thirdName");
cout << "-------------------" << endl;
cout << "Contents of objects" << endl;
cout << firstName.GetName() << endl;
cout << secondName->GetName() << endl;
cout << thirdName.GetName() << endl;
cout << fourthName.GetName() << endl;
cout << "-------------------" << endl ;
cout << "-- Last line of block --" << endl;
} // Block ends - third & fourth name destroyed
cout << "-- After block --" << endl;
delete secondName;
cout << "-- Last line of main() --" << endl;
} // firstName goes;
//*********************************************************
//
// Name class function definitions
//
// Constructor
Name::Name()
{
cout << "Constructor called" << endl;
name = 0;
}
// Destructor
Name::~Name()
{
cout << "Destructor called ";
cout << "name is " << GetName() << endl;
delete name; // Delete on zero pointer is safe
}
// Member function to store a name
//
void Name::SetName(const char* newName)
{
// First, remove any name that might already exist
// Use zero pointer to inidicate no name stored
// C++ will not destroy storage on a zero pointer
// "if (name)"
delete [] name;
// Create new storage
name = new char[strlen(newName) + 1]; // add 1 for
// terminator
strcpy(name,newName); // Copy data into new name
}
// Member function to get the stored name
// Coded to always return a safe value
const char * Name::GetName() const
{
if (name)
return name;
else
return "No name exists";
}
====================================
// Filename: CONDIT.CPP
// Finds the minimum and maximum values
// from the user's entered values
#include <iostream.h>
void main()
{
int val1, val2, min, max;
cout << "Enter a value: ";
cin >> val1;
cout << "Enter another value: ";
cin >> val2;
if (val1 < val2)
{ min = val1;
max = val2; }
else
{ max = val1;
min = val2; }
cout << endl << "Using if-else, the minimum is "
<< min << " and the maximum is " << max << endl;
min = (val1 < val2) ? val1 : val2;
max = (val2 > val1) ? val2 : val1;
cout << endl << "Using ?:, the minimum is "
<< min << " and the maximum is " << max << endl;
return;
}
=========================
// Filename: CONTACT.CPP
// Allow the display and entry of contacts
//
#include <iostream.h>
struct Contact
{
char name[50];
int age;
char phoneNo[15];
};
// Maximum number of contacts
const int MAXCONTACTS = 10;
// Prototypes
int AddContact(Contact& contact);
void DisplayContact(const Contact& contact);
void DisplayAllContacts(const Contact contacts[MAXCONTACTS],int count);
void main()
{
Contact contacts[MAXCONTACTS];
int count = 0;
while( count < MAXCONTACTS )// while more room
{
if (AddContact(contacts[count]))
count++;
else
break;
}
DisplayAllContacts(contacts,count);
}
//
// DisplayContact displays a single name
//
void DisplayContact(const Contact& contact)
{
cout << endl;
cout << "Name : " << contact.name << endl;
cout << "Age : " << contact.age << endl;
cout << "phone no: " << contact.phoneNo << endl;
cout << endl;
}
//
// DisplayAllContacts calls DisplayContact to show
// all entered names
//
void DisplayAllContacts(const Contact contacts[MAXCONTACTS],int count)
{
for (int i = 0; i < count; i++)
{
DisplayContact(contacts[i]);
}
}
//
// Add contact asks for one contact
//
int AddContact(Contact& contact)
{
char answer;
cout << "Do you want to add a contact [Y]es/[N]o: ";
cin >> answer;
cin.ignore(); // skip rubbish
if (answer == 'y' || answer == 'Y')
{
cout << "Name: ";
cin.getline(contact.name,30);
cout << "Phone no: ";
cin.getline(contact.phoneNo,15);
cout << "Age ";
cin >> contact.age;
cin.ignore();
return 1; // Added name ok
}
else
return 0; // Did not add name
}
==================================
// Filename: CONTACTO.CPP
// Allow the display and entry of contacts
// using OOP techniques
//
#include <iostream.h>
class Contact
{
public:
char name[50];
int age;
char phoneNo[15];
// Member function declarations (prototypes)
void AddContact();
void DisplayContact() const;
};
// Maximum number of contacts
const int MAXCONTACTS = 10;
// Global Prototypes
void DisplayAllContacts(const Contact contacts[MAXCONTACTS],int count);
void main()
{
Contact contacts[MAXCONTACTS];
char answer;
int count = 0;
while( count < MAXCONTACTS )// while more room
{
// Ask the user if they want to continue
cout << "Do you want to add a contact [Y]es/[N]o: ";
cin >> answer;
cin.ignore(80,'\n'); // skip rubbish
if (answer == 'y' || answer == 'Y')
{
// Add the information
contacts[count].AddContact();
count++;
}
else
break;
}
DisplayAllContacts(contacts,count);
}
//
// DisplayContact displays a single name
//
void Contact::DisplayContact() const
{
cout << endl;
cout << "Name : " << name << endl;
cout << "Age : " << age << endl;
cout << "phone no: " << phoneNo << endl;
cout << endl;
}
//
// DisplayAllContacts calls DisplayContact to show
// all entered names
//
void DisplayAllContacts(const Contact contacts[MAXCONTACTS],int count)
{
for (int i = 0; i < count; i++)
{
contacts[i].DisplayContact();
}
}
//
// Add contact asks for one contact
//
void Contact::AddContact()
{
cout << "Name: ";
cin.getline(name,30);
cout << "Phone no: ";
cin.getline(phoneNo,15);
cout << "Age ";
cin >> age;
cin.ignore();
}
====================
// Filename: CONTINU2.CPP
// Use continue when data is missing
// and break when the user finishes early
#include <iostream.h>
void main()
{
int count; // Loop control variable
float dSales; // Will hold each day's sales
float wSales=0; // Weekly total
// Set up the loop for a possible of five iterations
for (count=0; count<5; count++)
{
cout << "Enter the sales for day #" << (count+1)
<< " (-99 for none): ";
cin >> dSales;
if (dSales < -98.9) // User entered -99
{ continue; }
if (dSales < 0.0) // User entered -1
{ break; }
// The following statement executes ONLY if a
// valid daily sales total were just entered
wSales += dSales;
}
// Print the week's total
cout.precision(2);
cout.setf(ios::showpoint);
cout.setf(ios::fixed);
cout << "The weekly total is $" << wSales ;
return;
}
===========================
// Filename: CONTINUE.CPP
// Uses continue when data is missing
#include <iostream.h>
void main()
{
int count; // Loop control variable
float dSales; // Will hold each day's sales
float wSales = 0; // Weekly total
// Set up the loop for a possible five iterations
for (count = 0; count < 5; count++)
{
cout << "Enter the sales for day #" << (count + 1)
<< " (-99 for none): ";
cin >> dSales;
if (dSales < 0.0)
{ continue; }
// The following statement executes ONLY if a
// valid daily sales total was just entered
wSales += dSales;
}
// Print the week's total
cout.precision(2);
cout.setf(ios::showpoint);
cout.setf(ios::fixed);
cout << endl << "The weekly total is $"
<< wSales << endl;
return;
}
==========================
// Filename: COUNTRY.CPP
// Allocates ten country names on the heap.
#include <iostream.h>
#include <string.h>
void allMem(char * countries[10]);
void initMem(char * countries[10]);
void prMem(char * countries[10]);
void freeMem(char * countries[10]);
void main()
{
char * countries[10]; // Pointers to each country name
allMem(countries); // Allocate the memory
initMem(countries); // Store the country names
prMem(countries); // Print the country names
freeMem(countries); // Deallocate the memory
return;
}
//**********************************************************
void allMem(char * countries[10])
{
int ctr;
for (ctr=0; ctr<10; ctr++)
{ countries[ctr] = new char [15]; }
return;
}
//**********************************************************
void initMem(char * countries[10])
{
strcpy(countries[0], "Italy");
strcpy(countries[1], "Canada");
strcpy(countries[2], "New Zealand");
strcpy(countries[3], "France");
strcpy(countries[4], "Chile");
strcpy(countries[5], "Japan");
strcpy(countries[6], "Brazil");
strcpy(countries[7], "Mexico");
strcpy(countries[8], "Greece");
strcpy(countries[9], "Egypt");
return;
}
//**********************************************************
void prMem(char * countries[10])
{
int ctr;
cout << "Here are the countries stored on the heap:" << endl;
for (ctr=9; ctr>=0; ctr--)
{ cout << countries[ctr] << endl; }
return;
}
//**********************************************************
void freeMem(char * countries[10])
{
int ctr;
for (ctr=0; ctr<10; ctr++)
{ delete countries[ctr]; }
return;
}
===========================================
/* Filename: CPPADV.CPP */
// Shows some advantages and shortcuts of C++
#include <iostream.h>
#include <string.h>
struct People {
char * name; // Will allocate each name
int weight;
};
void getData(People dieter[4]);
void calcData(float & weight);
void prData(People dieter[4]);
void dealData(People dieter[4]);
main()
{
cout << "** Calculating a diet's weight loss **" << endl << endl << endl;
cout << "I'll ask for four people's names and";
cout << " weights and" << endl << "then calculate their expected";
cout << " weight loss after two weeks." << endl << endl;
// Define the four structure variables in the middle
// C++ programmers often use uppercase letters for structures
People dieter[4];
// Pass the variables to a function
// to allocate each name and fill the variables
getData(dieter);
// Pass the weights, by reference, to a calculate function
for (int ctr=0; ctr<4; ctr++) // Don't redefine control variable
{ // Pass just the weight of each array variable
// Due to a structure-passing conversion, save
// the structure's weight in a stand-alone variable
// before passing it. You cannot pass the middle of
// a structure by reference.
float passWeight = dieter[ctr].weight;
calcData(passWeight);
calcData(passWeight);
dieter[ctr].weight = passWeight; }
// Pass the variables to a print function
prData(dieter);
// Pass the variables to deallocate names
dealData(dieter);
return 0;
}
//**********************************************************
void getData(People dieter[4])
{
char buffer[80]; // For temporary input
for (int ctr=0; ctr<4; ctr++)
{ cout << "What is dieter #" << (ctr+1) << "'s name? ";
cin >> buffer;
// Make name pointer in each variable point to heap
dieter[ctr].name = new char[strlen(buffer)+1];
strcpy(dieter[ctr].name, buffer);
cout << "What is dieter #" << (ctr+1) << "'s weight? ";
cin >> dieter[ctr].weight;
}
return;
}
//**********************************************************
void calcData(float & weight)
{
weight *= .85;
return;
}
//**********************************************************
void prData(People dieter[4])
{
cout << endl << "Here are the predicted results after 3 weeks:";
for (int ctr=0; ctr<4; ctr++)
{
cout << "" << endl << dieter[ctr].name << " will weigh "
<< dieter[ctr].weight;
}
return;
}
//**********************************************************
void dealData(People dieter[4])
{
for (int ctr=0; ctr<4; ctr++)
{ delete dieter[ctr].name; }
return;
}
======================================
// Filename: CRREAD.CPP
// Creates a file then reads it
#include <fstream.h>
void main()
{
fstream myFile; // Inputs file pointer
char inChar;
myFile.open("c:\\data.txt", ios::out | ios::in);
if (!myFile)
{
cout << endl << "*** Error opening file ***" << endl;
return;
}
myFile << "Line 1 in DATA.TXT" << endl;
myFile << "Line 2 in DATA.TXT" << endl;
myFile << "Line 3 in DATA.TXT" << endl;
myFile << "Line 4 in DATA.TXT" << endl;
myFile.seekg(0L, ios::beg);
cout << "The file:" << endl;
while (myFile.get(inChar))
{ cout << inChar; } // Outputs characters to the screen
myFile.close();
return;
}