C++ Programing
// Outputting a string using stream insertion.
#include <iostream>
using std::cout;
int main()
{
cout << "Welcome to C++!\n";
return 0;
} // end function main
#include <iostream>
using std::cout;
int main()
{
cout << "Welcome to C++!\n";
return 0;
} // end function main
// Using the endl stream manipulator.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
cout << "Welcome to ";
cout << "C++!";
cout << endl; // end line stream manipulator
return 0;
} // end function main
// Cascading the overloaded << operator.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
cout << "47 plus 53 is " << ( 47 + 53 ) << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::endl;
int main()
{
cout << "47 plus 53 is " << ( 47 + 53 ) << endl;
return 0;
} // end function main
// Printing the address stored in a char* variable
#include <iostream>
using std::cout;
using std::endl;
int main()
{
const char *string = "test";
cout << "Value of string is: " << string
<< "\nValue of static_cast< void * >( string ) is: "
<< static_cast< void * >( string ) << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::endl;
int main()
{
const char *string = "test";
cout << "Value of string is: " << string
<< "\nValue of static_cast< void * >( string ) is: "
<< static_cast< void * >( string ) << endl;
return 0;
} // end function main
// Calculating the sum of two integers input from the keyboard
// with cin and the stream-extraction operator.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int x, y;
cout << "Enter two integers: ";
cin >> x >> y;
cout << "Sum of " << x << " and " << y << " is: "
<< ( x + y ) << endl;
return 0;
} // end function main
// with cin and the stream-extraction operator.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int x, y;
cout << "Enter two integers: ";
cin >> x >> y;
cout << "Sum of " << x << " and " << y << " is: "
<< ( x + y ) << endl;
return 0;
} // end function main
// Stream-extraction operator returning false on end-of-file.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int grade, highestGrade = -1;
cout << "Enter grade (enter end-of-file to end): ";
while ( cin >> grade ) {
if ( grade > highestGrade )
highestGrade = grade;
cout << "Enter grade (enter end-of-file to end): ";
} // end while
cout << "\n\nHighest grade is: " << highestGrade << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int grade, highestGrade = -1;
cout << "Enter grade (enter end-of-file to end): ";
while ( cin >> grade ) {
if ( grade > highestGrade )
highestGrade = grade;
cout << "Enter grade (enter end-of-file to end): ";
} // end while
cout << "\n\nHighest grade is: " << highestGrade << endl;
return 0;
} // end function main
// Using member functions get, put and eof.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
char c;
cout << "Before input, cin.eof() is " << cin.eof()
<< "\nEnter a sentence followed by end-of-file:\n";
while ( ( c = cin.get() ) != EOF )
cout.put( c );
cout << "\nEOF in this system is: " << c;
cout << "\nAfter input, cin.eof() is " << cin.eof() << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
char c;
cout << "Before input, cin.eof() is " << cin.eof()
<< "\nEnter a sentence followed by end-of-file:\n";
while ( ( c = cin.get() ) != EOF )
cout.put( c );
cout << "\nEOF in this system is: " << c;
cout << "\nAfter input, cin.eof() is " << cin.eof() << endl;
return 0;
} // end function main
// Contrasting input of a string with cin and cin.get.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
const int SIZE = 80;
char buffer1[ SIZE ], buffer2[ SIZE ];
cout << "Enter a sentence:\n";
cin >> buffer1;
cout << "\nThe string read with cin was:\n"
<< buffer1 << "\n\n";
cin.get( buffer2, SIZE );
cout << "The string read with cin.get was:\n"
<< buffer2 << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
const int SIZE = 80;
char buffer1[ SIZE ], buffer2[ SIZE ];
cout << "Enter a sentence:\n";
cin >> buffer1;
cout << "\nThe string read with cin was:\n"
<< buffer1 << "\n\n";
cin.get( buffer2, SIZE );
cout << "The string read with cin.get was:\n"
<< buffer2 << endl;
return 0;
} // end function main
// Character input with member function getline.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
const SIZE = 80;
char buffer[ SIZE ];
cout << "Enter a sentence:\n";
cin.getline( buffer, SIZE );
cout << "\nThe sentence entered is:\n" << buffer << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
const SIZE = 80;
char buffer[ SIZE ];
cout << "Enter a sentence:\n";
cin.getline( buffer, SIZE );
cout << "\nThe sentence entered is:\n" << buffer << endl;
return 0;
} // end function main
// Unformatted I/O with read, gcount and write.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
const int SIZE = 80;
char buffer[ SIZE ];
cout << "Enter a sentence:\n";
cin.read( buffer, 20 );
cout << "\nThe sentence entered was:\n";
cout.write( buffer, cin.gcount() );
cout << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
const int SIZE = 80;
char buffer[ SIZE ];
cout << "Enter a sentence:\n";
cin.read( buffer, 20 );
cout << "\nThe sentence entered was:\n";
cout.write( buffer, cin.gcount() );
cout << endl;
return 0;
} // end function main
// Using hex, oct, dec and setbase stream manipulators.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::hex;
using std::dec;
using std::oct;
using std::setbase;
int main()
{
int n;
cout << "Enter a decimal number: ";
cin >> n;
cout << n << " in hexadecimal is: "
<< hex << n << '\n'
<< dec << n << " in octal is: "
<< oct << n << '\n'
<< setbase( 10 ) << n << " in decimal is: "
<< n << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::hex;
using std::dec;
using std::oct;
using std::setbase;
int main()
{
int n;
cout << "Enter a decimal number: ";
cin >> n;
cout << n << " in hexadecimal is: "
<< hex << n << '\n'
<< dec << n << " in octal is: "
<< oct << n << '\n'
<< setbase( 10 ) << n << " in decimal is: "
<< n << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::ios;
using std::setiosflags;
using std::setprecision;
#include <cmath>
int main()
{
double root2 = sqrt( 2.0 );
int places;
cout << setiosflags( ios::fixed)
<< "Square root of 2 with precisions 0-9.\n"
<< "Precision set by the "
<< "precision member function:" << endl;
for ( places = 0; places <= 9; places++ ) {
cout.precision( places );
cout << root2 << '\n';
} // end for
cout << "\nPrecision set by the "
<< "setprecision manipulator:\n";
for ( places = 0; places <= 9; places++ )
cout << setprecision( places ) << root2 << '\n';
return 0;
} // end function main
using std::cout;
using std::cin;
using std::endl;
#include <iomanip>
using std::ios;
using std::setiosflags;
using std::setprecision;
#include <cmath>
int main()
{
double root2 = sqrt( 2.0 );
int places;
cout << setiosflags( ios::fixed)
<< "Square root of 2 with precisions 0-9.\n"
<< "Precision set by the "
<< "precision member function:" << endl;
for ( places = 0; places <= 9; places++ ) {
cout.precision( places );
cout << root2 << '\n';
} // end for
cout << "\nPrecision set by the "
<< "setprecision manipulator:\n";
for ( places = 0; places <= 9; places++ )
cout << setprecision( places ) << root2 << '\n';
return 0;
} // end function main
// Demonstrating the width member function
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int w = 4;
char string[ 10 ];
cout << "Enter a sentence:\n";
cin.width( 5 );
while ( cin >> string ) {
cout.width( w++ );
cout << string << endl;
cin.width( 5 );
} // end while
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int w = 4;
char string[ 10 ];
cout << "Enter a sentence:\n";
cin.width( 5 );
while ( cin >> string ) {
cout.width( w++ );
cout << string << endl;
cin.width( 5 );
} // end while
return 0;
} // end function main
// Creating and testing user-defined, nonparameterized
// stream manipulators.
#include <iostream>
using std::ostream;
using std::cout;
using std::flush;
// bell manipulator (using escape sequence \a)
ostream& bell( ostream& output ) { return output << '\a'; }
// ret manipulator (using escape sequence \r)
ostream& ret( ostream& output ) { return output << '\r'; }
// tab manipulator (using escape sequence \t)
ostream& tab( ostream& output ) { return output << '\t'; }
// endLine manipulator (using escape sequence \n
// and the flush member function)
ostream& endLine( ostream& output )
{
return output << '\n' << flush;
} // end function endLine
int main()
{
cout << "Testing the tab manipulator:" << endLine
<< 'a' << tab << 'b' << tab << 'c' << endLine
<< "Testing the ret and bell manipulators:"
<< endLine << "..........";
cout << bell;
cout << ret << "-----" << endLine;
return 0;
} // end function main
// stream manipulators.
#include <iostream>
using std::ostream;
using std::cout;
using std::flush;
// bell manipulator (using escape sequence \a)
ostream& bell( ostream& output ) { return output << '\a'; }
// ret manipulator (using escape sequence \r)
ostream& ret( ostream& output ) { return output << '\r'; }
// tab manipulator (using escape sequence \t)
ostream& tab( ostream& output ) { return output << '\t'; }
// endLine manipulator (using escape sequence \n
// and the flush member function)
ostream& endLine( ostream& output )
{
return output << '\n' << flush;
} // end function endLine
int main()
{
cout << "Testing the tab manipulator:" << endLine
<< 'a' << tab << 'b' << tab << 'c' << endLine
<< "Testing the ret and bell manipulators:"
<< endLine << "..........";
cout << bell;
cout << ret << "-----" << endLine;
return 0;
} // end function main
// Controlling the printing of trailing zeros and decimal
// points for floating-point values.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::ios;
#include <cmath>
int main()
{
cout << "Before setting the ios::showpoint flag\n"
<< "9.9900 prints as: " << 9.9900
<< "\n9.9000 prints as: " << 9.9000
<< "\n9.0000 prints as: " << 9.0000
<< "\n\nAfter setting the ios::showpoint flag\n";
cout.setf( ios::showpoint );
cout << "9.9900 prints as: " << 9.9900
<< "\n9.9000 prints as: " << 9.9000
<< "\n9.0000 prints as: " << 9.0000 << endl;
return 0;
} // end function main
// points for floating-point values.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::ios;
#include <cmath>
int main()
{
cout << "Before setting the ios::showpoint flag\n"
<< "9.9900 prints as: " << 9.9900
<< "\n9.9000 prints as: " << 9.9000
<< "\n9.0000 prints as: " << 9.0000
<< "\n\nAfter setting the ios::showpoint flag\n";
cout.setf( ios::showpoint );
cout << "9.9900 prints as: " << 9.9900
<< "\n9.9000 prints as: " << 9.9000
<< "\n9.0000 prints as: " << 9.0000 << endl;
return 0;
} // end function main
// Left-justification and right-justification.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::ios;
using std::setw;
using std::setiosflags;
using std::resetiosflags;
int main()
{
int x = 12345;
cout << "Default is right justified:\n"
<< setw(10) << x << "\n\nUSING MEMBER FUNCTIONS"
<< "\nUse setf to set ios::left:\n" << setw(10);
cout.setf( ios::left, ios::adjustfield );
cout << x << "\nUse unsetf to restore default:\n";
cout.unsetf( ios::left );
cout << setw( 10 ) << x
<< "\n\nUSING PARAMETERIZED STREAM MANIPULATORS"
<< "\nUse setiosflags to set ios::left:\n"
<< setw( 10 ) << setiosflags( ios::left ) << x
<< "\nUse resetiosflags to restore default:\n"
<< setw( 10 ) << resetiosflags( ios::left )
<< x << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::ios;
using std::setw;
using std::setiosflags;
using std::resetiosflags;
int main()
{
int x = 12345;
cout << "Default is right justified:\n"
<< setw(10) << x << "\n\nUSING MEMBER FUNCTIONS"
<< "\nUse setf to set ios::left:\n" << setw(10);
cout.setf( ios::left, ios::adjustfield );
cout << x << "\nUse unsetf to restore default:\n";
cout.unsetf( ios::left );
cout << setw( 10 ) << x
<< "\n\nUSING PARAMETERIZED STREAM MANIPULATORS"
<< "\nUse setiosflags to set ios::left:\n"
<< setw( 10 ) << setiosflags( ios::left ) << x
<< "\nUse resetiosflags to restore default:\n"
<< setw( 10 ) << resetiosflags( ios::left )
<< x << endl;
return 0;
} // end function main
// Printing an integer with internal spacing and
// forcing the plus sign.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::ios;
using std::setiosflags;
using std::setw;
int main()
{
cout << setiosflags( ios::internal | ios::showpos )
<< setw( 10 ) << 123 << endl;
return 0;
} // end function main
// forcing the plus sign.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::ios;
using std::setiosflags;
using std::setw;
int main()
{
cout << setiosflags( ios::internal | ios::showpos )
<< setw( 10 ) << 123 << endl;
return 0;
} // end function main
// Using the fill member function and the setfill
// manipulator to change the padding character for
// fields larger than the values being printed.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::ios;
using std::setw;
using std::hex;
using std::dec;
using std::setfill;
int main()
{
int x = 10000;
cout << x << " printed as int right and left justified\n"
<< "and as hex with internal justification.\n"
<< "Using the default pad character (space):\n";
cout.setf( ios::showbase );
cout << setw( 10 ) << x << '\n';
cout.setf( ios::left, ios::adjustfield );
cout << setw( 10 ) << x << '\n';
cout.setf( ios::internal, ios::adjustfield );
cout << setw( 10 ) << hex << x;
cout << "\n\nUsing various padding characters:\n";
cout.setf( ios::right, ios::adjustfield );
cout.fill( '*' );
cout << setw( 10 ) << dec << x << '\n';
cout.setf( ios::left, ios::adjustfield );
cout << setw( 10 ) << setfill( '%' ) << x << '\n';
cout.setf( ios::internal, ios::adjustfield );
cout << setw( 10 ) << setfill( '^' ) << hex << x << endl;
return 0;
} // end function main
// manipulator to change the padding character for
// fields larger than the values being printed.
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::ios;
using std::setw;
using std::hex;
using std::dec;
using std::setfill;
int main()
{
int x = 10000;
cout << x << " printed as int right and left justified\n"
<< "and as hex with internal justification.\n"
<< "Using the default pad character (space):\n";
cout.setf( ios::showbase );
cout << setw( 10 ) << x << '\n';
cout.setf( ios::left, ios::adjustfield );
cout << setw( 10 ) << x << '\n';
cout.setf( ios::internal, ios::adjustfield );
cout << setw( 10 ) << hex << x;
cout << "\n\nUsing various padding characters:\n";
cout.setf( ios::right, ios::adjustfield );
cout.fill( '*' );
cout << setw( 10 ) << dec << x << '\n';
cout.setf( ios::left, ios::adjustfield );
cout << setw( 10 ) << setfill( '%' ) << x << '\n';
cout.setf( ios::internal, ios::adjustfield );
cout << setw( 10 ) << setfill( '^' ) << hex << x << endl;
return 0;
} // end function main
// Using the ios::showbase flag
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::ios;
using std::setiosflags;
using std::oct;
using std::hex;
int main()
{
int x = 100;
cout << setiosflags( ios::showbase )
<< "Printing integers preceded by their base:\n"
<< x << '\n'
<< oct << x << '\n'
<< hex << x << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::ios;
using std::setiosflags;
using std::oct;
using std::hex;
int main()
{
int x = 100;
cout << setiosflags( ios::showbase )
<< "Printing integers preceded by their base:\n"
<< x << '\n'
<< oct << x << '\n'
<< hex << x << endl;
return 0;
} // end function main
// Displaying floating-point values in system default,
// scientific, and fixed formats.
#include <iostream>
using std::cout;
using std::endl;
using std::ios;
int main()
{
double x = .001234567, y = 1.946e9;
cout << "Displayed in default format:\n"
<< x << '\t' << y << '\n';
cout.setf( ios::scientific, ios::floatfield );
cout << "Displayed in scientific format:\n"
<< x << '\t' << y << '\n';
cout.unsetf( ios::scientific );
cout << "Displayed in default format after unsetf:\n"
<< x << '\t' << y << '\n';
cout.setf( ios::fixed, ios::floatfield );
cout << "Displayed in fixed format:\n"
<< x << '\t' << y << endl;
return 0;
} // end function main
// scientific, and fixed formats.
#include <iostream>
using std::cout;
using std::endl;
using std::ios;
int main()
{
double x = .001234567, y = 1.946e9;
cout << "Displayed in default format:\n"
<< x << '\t' << y << '\n';
cout.setf( ios::scientific, ios::floatfield );
cout << "Displayed in scientific format:\n"
<< x << '\t' << y << '\n';
cout.unsetf( ios::scientific );
cout << "Displayed in default format after unsetf:\n"
<< x << '\t' << y << '\n';
cout.setf( ios::fixed, ios::floatfield );
cout << "Displayed in fixed format:\n"
<< x << '\t' << y << endl;
return 0;
} // end function main
// Using the ios::uppercase flag
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setiosflags;
using std::ios;
using std::hex;
int main()
{
cout << setiosflags( ios::uppercase )
<< "Printing uppercase letters in scientific\n"
<< "notation exponents and hexadecimal values:\n"
<< 4.345e10 << '\n' << hex << 123456789 << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::endl;
#include <iomanip>
using std::setiosflags;
using std::ios;
using std::hex;
int main()
{
cout << setiosflags( ios::uppercase )
<< "Printing uppercase letters in scientific\n"
<< "notation exponents and hexadecimal values:\n"
<< 4.345e10 << '\n' << hex << 123456789 << endl;
return 0;
} // end function main
// Demonstrating the flags member function.
#include <iostream>
using std::cout;
using std::endl;
using std::ios;
int main()
{
int i = 1000;
double d = 0.0947628;
cout << "The value of the flags variable is: "
<< cout.flags()
<< "\nPrint int and double in original format:\n"
<< i << '\t' << d << "\n\n";
long originalFormat =
cout.flags( ios::oct | ios::scientific );
cout << "The value of the flags variable is: "
<< cout.flags()
<< "\nPrint int and double in a new format\n"
<< "specified using the flags member function:\n"
<< i << '\t' << d << "\n\n";
cout.flags( originalFormat );
cout << "The value of the flags variable is: "
<< cout.flags()
<< "\nPrint values in original format again:\n"
<< i << '\t' << d << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::endl;
using std::ios;
int main()
{
int i = 1000;
double d = 0.0947628;
cout << "The value of the flags variable is: "
<< cout.flags()
<< "\nPrint int and double in original format:\n"
<< i << '\t' << d << "\n\n";
long originalFormat =
cout.flags( ios::oct | ios::scientific );
cout << "The value of the flags variable is: "
<< cout.flags()
<< "\nPrint int and double in a new format\n"
<< "specified using the flags member function:\n"
<< i << '\t' << d << "\n\n";
cout.flags( originalFormat );
cout << "The value of the flags variable is: "
<< cout.flags()
<< "\nPrint values in original format again:\n"
<< i << '\t' << d << endl;
return 0;
} // end function main
// Testing error states.
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int x;
cout << "Before a bad input operation:"
<< "\ncin.rdstate(): " << cin.rdstate()
<< "\n cin.eof(): " << cin.eof()
<< "\n cin.fail(): " << cin.fail()
<< "\n cin.bad(): " << cin.bad()
<< "\n cin.good(): " << cin.good()
<< "\n\nExpects an integer, but enter a character: ";
cin >> x;
cout << "\nAfter a bad input operation:"
<< "\ncin.rdstate(): " << cin.rdstate()
<< "\n cin.eof(): " << cin.eof()
<< "\n cin.fail(): " << cin.fail()
<< "\n cin.bad(): " << cin.bad()
<< "\n cin.good(): " << cin.good() << "\n\n";
cin.clear();
cout << "After cin.clear()"
<< "\ncin.fail(): " << cin.fail()
<< "\ncin.good(): " << cin.good() << endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main()
{
int x;
cout << "Before a bad input operation:"
<< "\ncin.rdstate(): " << cin.rdstate()
<< "\n cin.eof(): " << cin.eof()
<< "\n cin.fail(): " << cin.fail()
<< "\n cin.bad(): " << cin.bad()
<< "\n cin.good(): " << cin.good()
<< "\n\nExpects an integer, but enter a character: ";
cin >> x;
cout << "\nAfter a bad input operation:"
<< "\ncin.rdstate(): " << cin.rdstate()
<< "\n cin.eof(): " << cin.eof()
<< "\n cin.fail(): " << cin.fail()
<< "\n cin.bad(): " << cin.bad()
<< "\n cin.good(): " << cin.good() << "\n\n";
cin.clear();
cout << "After cin.clear()"
<< "\ncin.fail(): " << cin.fail()
<< "\ncin.good(): " << cin.good() << endl;
return 0;
} // end function main
// Test driver for Stack template
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include "tstack1.h"
int main()
{
Stack< double > doubleStack( 5 );
double f = 1.1;
cout << "Pushing elements onto doubleStack\n";
while ( doubleStack.push( f ) ) { // success true returned
cout << f << ' ';
f += 1.1;
} // end while
cout << "\nStack is full. Cannot push " << f
<< "\n\nPopping elements from doubleStack\n";
while ( doubleStack.pop( f ) ) // success true returned
cout << f << ' ';
cout << "\nStack is empty. Cannot pop\n";
Stack< int > intStack;
int i = 1;
cout << "\nPushing elements onto intStack\n";
while ( intStack.push( i ) ) { // success true returned
cout << i << ' ';
++i;
} // end while
cout << "\nStack is full. Cannot push " << i
<< "\n\nPopping elements from intStack\n";
while ( intStack.pop( i ) ) // success true returned
cout << i << ' ';
cout << "\nStack is empty. Cannot pop\n";
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include "tstack1.h"
int main()
{
Stack< double > doubleStack( 5 );
double f = 1.1;
cout << "Pushing elements onto doubleStack\n";
while ( doubleStack.push( f ) ) { // success true returned
cout << f << ' ';
f += 1.1;
} // end while
cout << "\nStack is full. Cannot push " << f
<< "\n\nPopping elements from doubleStack\n";
while ( doubleStack.pop( f ) ) // success true returned
cout << f << ' ';
cout << "\nStack is empty. Cannot pop\n";
Stack< int > intStack;
int i = 1;
cout << "\nPushing elements onto intStack\n";
while ( intStack.push( i ) ) { // success true returned
cout << i << ' ';
++i;
} // end while
cout << "\nStack is full. Cannot push " << i
<< "\n\nPopping elements from intStack\n";
while ( intStack.pop( i ) ) // success true returned
cout << i << ' ';
cout << "\nStack is empty. Cannot pop\n";
return 0;
} // end function main
// Test driver for Stack template.
// Function main uses a function template to manipulate
// objects of type Stack< T >.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include "tstack1.h"
// Function template to manipulate Stack< T >
template< class T >
void testStack(
Stack< T > &theStack, // reference to the Stack< T >
T value, // initial value to be pushed
T increment, // increment for subsequent values
const char *stackName ) // name of the Stack < T > object
{
cout << "\nPushing elements onto " << stackName << '\n';
while ( theStack.push( value ) ) { // success true returned
cout << value << ' ';
value += increment;
} // end while
cout << "\nStack is full. Cannot push " << value
<< "\n\nPopping elements from " << stackName << '\n';
while ( theStack.pop( value ) ) // success true returned
cout << value << ' ';
cout << "\nStack is empty. Cannot pop\n";
} // end function template testStack
int main()
{
Stack< double > doubleStack( 5 );
Stack< int > intStack;
testStack( doubleStack, 1.1, 1.1, "doubleStack" );
testStack( intStack, 1, 1, "intStack" );
return 0;
} // end function main
// Function main uses a function template to manipulate
// objects of type Stack< T >.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include "tstack1.h"
// Function template to manipulate Stack< T >
template< class T >
void testStack(
Stack< T > &theStack, // reference to the Stack< T >
T value, // initial value to be pushed
T increment, // increment for subsequent values
const char *stackName ) // name of the Stack < T > object
{
cout << "\nPushing elements onto " << stackName << '\n';
while ( theStack.push( value ) ) { // success true returned
cout << value << ' ';
value += increment;
} // end while
cout << "\nStack is full. Cannot push " << value
<< "\n\nPopping elements from " << stackName << '\n';
while ( theStack.pop( value ) ) // success true returned
cout << value << ' ';
cout << "\nStack is empty. Cannot pop\n";
} // end function template testStack
int main()
{
Stack< double > doubleStack( 5 );
Stack< int > intStack;
testStack( doubleStack, 1.1, 1.1, "doubleStack" );
testStack( intStack, 1, 1, "intStack" );
return 0;
} // end function main
// A simple exception handling example.
// Checking for a divide-by-zero exception.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
// Class DivideByZeroException to be used in exception
// handling for throwing an exception on a division by zero.
class DivideByZeroException {
public:
DivideByZeroException()
: message( "attempted to divide by zero" ) { }
const char *what() const { return message; }
private:
const char *message;
}; // end class DivideByZeroException
// Definition of function quotient. Demonstrates throwing
// an exception when a divide-by-zero exception is encountered.
double quotient( int numerator, int denominator )
{
if ( denominator == 0 )
throw DivideByZeroException();
return static_cast< double > ( numerator ) / denominator;
} // end function quotient
// Driver program
int main()
{
int number1, number2;
double result;
cout << "Enter two integers (end-of-file to end): ";
while ( cin >> number1 >> number2 ) {
// the try block wraps the code that may throw an
// exception and the code that should not execute
// if an exception occurs
try {
result = quotient( number1, number2 );
cout << "The quotient is: " << result << endl;
} // end try
catch ( DivideByZeroException ex ) { // exception handler
cout << "Exception occurred: " << ex.what() << '\n';
} // end catch
cout << "\nEnter two integers (end-of-file to end): ";
} // end while
cout << endl;
return 0; // terminate normally
} // end function main
// Checking for a divide-by-zero exception.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
// Class DivideByZeroException to be used in exception
// handling for throwing an exception on a division by zero.
class DivideByZeroException {
public:
DivideByZeroException()
: message( "attempted to divide by zero" ) { }
const char *what() const { return message; }
private:
const char *message;
}; // end class DivideByZeroException
// Definition of function quotient. Demonstrates throwing
// an exception when a divide-by-zero exception is encountered.
double quotient( int numerator, int denominator )
{
if ( denominator == 0 )
throw DivideByZeroException();
return static_cast< double > ( numerator ) / denominator;
} // end function quotient
// Driver program
int main()
{
int number1, number2;
double result;
cout << "Enter two integers (end-of-file to end): ";
while ( cin >> number1 >> number2 ) {
// the try block wraps the code that may throw an
// exception and the code that should not execute
// if an exception occurs
try {
result = quotient( number1, number2 );
cout << "The quotient is: " << result << endl;
} // end try
catch ( DivideByZeroException ex ) { // exception handler
cout << "Exception occurred: " << ex.what() << '\n';
} // end catch
cout << "\nEnter two integers (end-of-file to end): ";
} // end while
cout << endl;
return 0; // terminate normally
} // end function main
// Demonstration of rethrowing an exception.
#include <iostream>
using std::cout;
using std::endl;
#include <exception>
using std::exception;
void throwException()
{
// Throw an exception and immediately catch it.
try {
cout << "Function throwException\n";
throw exception(); // generate exception
} // end try
catch( exception e )
{
cout << "Exception handled in function throwException\n";
throw; // rethrow exception for further processing
} // end catch
cout << "This also should not print\n";
} // end function throwException
int main()
{
try {
throwException();
cout << "This should not print\n";
} // end try
catch ( exception e )
{
cout << "Exception handled in main\n";
} // end catch
cout << "Program control continues after catch in main"
<< endl;
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::endl;
#include <exception>
using std::exception;
void throwException()
{
// Throw an exception and immediately catch it.
try {
cout << "Function throwException\n";
throw exception(); // generate exception
} // end try
catch( exception e )
{
cout << "Exception handled in function throwException\n";
throw; // rethrow exception for further processing
} // end catch
cout << "This also should not print\n";
} // end function throwException
int main()
{
try {
throwException();
cout << "This should not print\n";
} // end try
catch ( exception e )
{
cout << "Exception handled in main\n";
} // end catch
cout << "Program control continues after catch in main"
<< endl;
return 0;
} // end function main
// Demonstrating stack unwinding.
#include <iostream>
using std::cout;
using std::endl;
#include <stdexcept>
using std::runtime_error;
void function3() throw ( runtime_error )
{
throw runtime_error( "runtime_error in function3" );
} // end function function3
void function2() throw ( runtime_error )
{
function3();
} // end function function2
void function1() throw ( runtime_error )
{
function2();
} // end function function1
int main()
{
try {
function1();
} // end try
catch ( runtime_error e )
{
cout << "Exception occurred: " << e.what() << endl;
} // end catch
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::endl;
#include <stdexcept>
using std::runtime_error;
void function3() throw ( runtime_error )
{
throw runtime_error( "runtime_error in function3" );
} // end function function3
void function2() throw ( runtime_error )
{
function3();
} // end function function2
void function1() throw ( runtime_error )
{
function2();
} // end function function1
int main()
{
try {
function1();
} // end try
catch ( runtime_error e )
{
cout << "Exception occurred: " << e.what() << endl;
} // end catch
return 0;
} // end function main
// Demonstrating new returning 0
// when memory is not allocated
#include <iostream>
using std::cout;
int main()
{
double *ptr[ 50 ];
for ( int i = 0; i < 50; i++ ) {
ptr[ i ] = new double[ 5000000 ];
if ( ptr[ i ] == 0 ) { // new failed to allocate memory
cout << "Memory allocation failed for ptr[ "
<< i << " ]\n";
break;
} // end if
else
cout << "Allocated 5000000 doubles in ptr[ "
<< i << " ]\n";
} // end for
return 0;
} // end function main
// when memory is not allocated
#include <iostream>
using std::cout;
int main()
{
double *ptr[ 50 ];
for ( int i = 0; i < 50; i++ ) {
ptr[ i ] = new double[ 5000000 ];
if ( ptr[ i ] == 0 ) { // new failed to allocate memory
cout << "Memory allocation failed for ptr[ "
<< i << " ]\n";
break;
} // end if
else
cout << "Allocated 5000000 doubles in ptr[ "
<< i << " ]\n";
} // end for
return 0;
} // end function main
// Demonstrating new throwing bad_alloc
// when memory is not allocated
#include <iostream>
using std::cout;
using std::endl;
#include <new>
using std::bad_alloc;
int main()
{
double *ptr[ 50 ];
try {
for ( int i = 0; i < 50; i++ ) {
ptr[ i ] = new double[ 5000000 ];
cout << "Allocated 5000000 doubles in ptr[ "
<< i << " ]\n";
} // end for
} // end try
catch ( bad_alloc exception ) {
cout << "Exception occurred: "
<< exception.what() << endl;
} // end catch
return 0;
} // end function main
// when memory is not allocated
#include <iostream>
using std::cout;
using std::endl;
#include <new>
using std::bad_alloc;
int main()
{
double *ptr[ 50 ];
try {
for ( int i = 0; i < 50; i++ ) {
ptr[ i ] = new double[ 5000000 ];
cout << "Allocated 5000000 doubles in ptr[ "
<< i << " ]\n";
} // end for
} // end try
catch ( bad_alloc exception ) {
cout << "Exception occurred: "
<< exception.what() << endl;
} // end catch
return 0;
} // end function main
// Demonstrating set_new_handler
#include <iostream>
using std::cout;
using std::cerr;
#include <new>
#include <cstdlib>
using std::set_new_handler;
void customNewHandler()
{
cerr << "customNewHandler was called";
abort();
} // end function customNewHandler
int main()
{
double *ptr[ 50 ];
set_new_handler( customNewHandler );
for ( int i = 0; i < 50; i++ ) {
ptr[ i ] = new double[ 5000000 ];
cout << "Allocated 5000000 doubles in ptr[ "
<< i << " ]\n";
} // end for
return 0;
} // end function main
#include <iostream>
using std::cout;
using std::cerr;
#include <new>
#include <cstdlib>
using std::set_new_handler;
void customNewHandler()
{
cerr << "customNewHandler was called";
abort();
} // end function customNewHandler
int main()
{
double *ptr[ 50 ];
set_new_handler( customNewHandler );
for ( int i = 0; i < 50; i++ ) {
ptr[ i ] = new double[ 5000000 ];
cout << "Allocated 5000000 doubles in ptr[ "
<< i << " ]\n";
} // end for
return 0;
} // end function main