OBJECT-ORIENTED
PROGRAMMING IN C++
Ahmed Mohamed Sayed Ahmed
Computer lecturer
Cisco Certified Academy Instructor
Contents
2
Chapter
Content
Chapter 1
The Big Picture
Chapter 2
C++ Programming Basics
Chapter 3
Loops and Decisions
Chapter 4
Structures
Chapter 5
Functions
Chapter 6
Objects and Classes
Chapter 7
Arrays and Strings
Chapter 8
Operator Overloading
Chapter 9
Inheritance
Chapter 10 Pointers
Chapter 11 Virtual Functions and Polymorphism
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
The Chapter Contents
3
1.
2.
3.
4.
5.
6.
7.
8.
Chapter 2: C++ Programming Basics
Getting Started
Basic Program Construction
Output Using cout
Directives
Comments
Integer Variables
Character Variables
Input with cin
Ahmed Mohamed Sayed Ahmed - Computer lecturer
9. Floating Point Types
10.Type bool
11.The setw Manipulator
12.Variable Type Summary
13.Type Conversion
14.Arithmetic Operators
15.Library Functions
Thursday, November 22, 2012
1. Getting Started
4
Chapter 2: C++ Programming Basics
We will use a compiler from Visual Studio 6.0 program.
We can download the Visual Studio 6.0 program, for free,
from these links:
http://www.4shared.com/zip/jxr5H2F-/Visual_Studio_60.html
(Free Register required)
https://rapidshare.com/files/3614028324/Visual%20Studio%206.0.zip
(Register not required)
Open the program by choose:
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
5
Chapter 2: C++ Programming Basics
The Program Interface:
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
6
Chapter 2: C++ Programming Basics
Open new Project by choose:
File
New
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
7
Chapter 2: C++ Programming Basics
From Projects tab, choose Win32 Console Application.
2
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
8
Chapter 2: C++ Programming Basics
In Project name box, write a name for your project, for example
My Project. Then press OK button.
4
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
9
Chapter 2: C++ Programming Basics
Press on Finish button to continue
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
10
Chapter 2: C++ Programming Basics
Press on OK button to finish creating the project.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
11
Chapter 2: C++ Programming Basics
Open new File by choose:
File
New
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
12
Chapter 2: C++ Programming Basics
From Files tab, choose C++ Source File.
10
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
13
Chapter 2: C++ Programming Basics
In File name box, write a name for your source code file, for example
FIRST. Then press OK button.
11
12
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
14
Chapter 2: C++ Programming Basics
The compiler is ready now to write your source code.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
15
Chapter 2: C++ Programming Basics
Compilers take source code and transform it into
executable files, which your computer can run as it does
other programs.
Source files are text files (extension .CPP) that we will
learn how to write it through our course.
Executable files have the .EXE extension, and can be
executed either from within your compiler, or directly
alone.
A DSW file contains the text of a program being
developed in the Microsoft C++ language. You will use
the file with DSW (Microsoft Developer Studio
Workspace) extension to open the project you created.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
2. Basic Program Construction
16
Chapter 2: C++ Programming Basics
Write the following code that will simply prints a
sentence on the screen.
#include<iostream>
using namespace std;
int main( )
{
cout<<"Hello World. "<<endl;
system("pause");
return 0;
Output:
Hello World.
}
Press any key to continue
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
2. Basic Program Construction
17
Chapter 2: C++ Programming Basics
There are two steps to complete building our first
project:
1. Press F7, or from Build menu choose Build FIRST.exe to
find out errors in our code.
2. Press Ctrl+F5, or from Build menu choose Execute
FIRST.exe to build and execute our project.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
18
Chapter 2: C++ Programming Basics
main function
The parentheses following the word main are the
distinguishing feature of a function. Without the
parentheses the compiler would think that main refers to
a variable.
Well put parentheses following the function name. Later
on well see that the parentheses arent always empty.
Theyre used to hold function arguments: values passed
from the calling program to the function.
The word int preceding the function name indicates that
this particular function has a return value of type int.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
19
Chapter 2: C++ Programming Basics
Braces and the Function Body
The body of a function is surrounded by braces.
These braces play the same role as the BEGIN and END
keywords in some other languages: They surround or delimit
a block of program statements.
Always start with main ( )
When you run a C++ program, the first statement executed
will be at the beginning of a function called main ( ).
The program may consist of many functions, classes, and
other program elements, but on startup, control always goes
to main ( ).
If there is no function called main ( ) in your program, an
error will be reported when you run the program.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
1. Getting Started
20
Chapter 2: C++ Programming Basics
Program Statements
A semicolon signals the end of the statement. If you
leave out the semicolon, the compiler will often
(although not always) signal an error.
The last statement in the function body is return 0;. This
tells main ( ) to return the value 0 to whoever called it,
in this case the operating system or compiler.
In older versions of C++ you could give main ( ) the
return type of void and dispense with the return
statement, but this is not considered correct in Standard
C++.
You can put several statements on one line, separated
by any number of spaces or tabs.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
2. Basic Program Construction
21
Chapter 2: C++ Programming Basics
#include<iostream>
using namespace std;
int main( )
{ cout<<"Hello World. "<<endl; system("pause"); return 0; }
#include
<iostream>
using namespace std;
int main( )
{ cout<<"Hello World. "<<endl; system("pause"); return 0; }
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
3. Output Using cout
22
Chapter 2: C++ Programming Basics
As you have seen, the statement:
cout<<"Hello World. "<<endl;
causes the phrase in quotation
marks to be displayed on the
screen.
The identifier cout (pronounced C out) is actually an
object. It is predefined in C++ to correspond to the
standard output stream.
The operator << is called the insertion or put to operator.
It directs the contents of the variable on its right to the
object on its left. In FIRST project, it directs the string
constant Hello World. to cout, which sends it to the
display.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
3. Output Using cout
23
Chapter 2: C++ Programming Basics
As you have seen, the endl in statement:
cout<<"Hello World. "<<endl;
causes the next text output to be displayed on a new line.
We use it here so that the phrases such as Press any key to
continue , inserted by some compilers for display after
the program terminates, will appear on a new line.
We can use another way to display the same output:
cout<<"Hello World. "<<'\n';
or
cout<<"Hello World. \n";
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
4. Directives
24
Chapter 2: C++ Programming Basics
The two lines that begin the FIRST program are directives.
#include<iostream>
using namespace std;
The first is a preprocessor directive, and the second is a using
directive. Theyre not part of the basic C++ language, but
theyre necessary anyway.
The preprocessor directive #include tells the compiler to insert
another file into your source file. In effect, the #include
directive is replaced by the contents of the file indicated.
The type file usually included by #include is called a header
file.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
4. Directives
25
Chapter 2: C++ Programming Basics
#include<iostream>
In the FIRST example, the preprocessor directive #include
tells the compiler to add the source file iostream to the
FIRST.CPP source file before compiling.
iostream is an example of a header file. Its concerned
with basic input/output operations, and contains
declarations that are needed by the cout identifier and
the << operator.
Without these declarations, the compiler wont recognize
cout and will think << is being used incorrectly.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
4. Directives
26
Chapter 2: C++ Programming Basics
using namespace std;
The using directive says that all the program statements
that follow are within the std namespace.
If we didnt use the using directive, we would need to add
the std name to many program elements. For example:
std::cout<<"Hello World. "<<endl;
To avoid adding std:: dozens of times in programs we use
the using directive instead.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
5. Comments
27
Chapter 2: C++ Programming Basics
Comments are an important part of any program. They
help the person writing a program, and anyone else who
must read the source file, understand whats going on.
The compiler ignores comments, so they do not add to the
file size or execution time of the executable program.
A comment can start at the beginning of the line or on the
same line following a program statement.
We can write the comments using any languages we can
easily understand it.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
5. Comments
28
Chapter 2: C++ Programming Basics
The first comment style start with a double slash symbol //
and terminate at the end of the line.
// comments.cpp
// demonstrates comments
#include<iostream>
//preprocessor directive
using namespace std;
//using directive
int main( )
//function name main
{
//start function body
cout<<"Hello World. "<<endl;
//
system("pause");
//statement
return 0;
//statement
}
//end function body
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
5. Comments
29
Chapter 2: C++ Programming Basics
Theres a second comment style available in C++. This
type of comment (the only comment originally available in
C) begins with the /* character pair and ends with */ (not
with the end of the line).
This is a good approach to making a comment out of a
large text passage, since it saves inserting the // symbol
on every line.
/* this is a
/* this is an old-style comment */
Ahmed Mohamed Sayed Ahmed - Computer lecturer
potentially
very long
multiline
comment
*/
Thursday, November 22, 2012
5. Comments
30
Chapter 2: C++ Programming Basics
You can also insert a /* . */ comment anywhere within
the text of a program line:
func1( )
{ /* empty function body */ }
If you attempt to use the // style comment in this case, the
closing brace wont be visible to the compiler. Since a //
style comment runs to the end of the line, and the code
wont compile correctly.
func1( )
{ // empty function body }
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
6. Integer Variables
31
Chapter 2: C++ Programming Basics
Variables are the most fundamental part of any language.
A variable has a symbolic name and can be given a
variety of values.
Variables are located in particular places in the
computers memory.
When a variable is given a value, that value is actually
placed in the memory space assigned to the variable.
Most popular languages use the same general variable
types, such as integers, floating-point numbers, and
characters, so you are probably already familiar with the
ideas behind them.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
6. Integer Variables
32
Chapter 2: C++ Programming Basics
Variable Names
You can use uppercase and lowercase letters, and the digits
from 1 to 9. You can also use the underscore (_).
The first character must be a letter or underscore.
The compiler distinguishes between uppercase and
lowercase letters, so Var is not the same as var or VAR.
You cant use a C++ keyword as a variable name. A
keyword is a predefined word with a special meaning. int,
class, if, and while are examples of keywords.
A variables name should make clear to anyone reading the
listing the variables purpose and how it is used.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
6. Integer Variables
33
Chapter 2: C++ Programming Basics
Integer variables represent integer numbers like 1, 30,000, and
27. Such numbers are used for counting discrete numbers of
objects, like 11 pencils or 100 students.
Unlike floating-point numbers, integers have no fractional part.
Integer variables exist in several sizes, but the most commonly
used is type int. The amount of memory occupied by the integer
types is system dependent. On a 32-bit system such as Windows,
an int occupies 4 bytes (byte = 8 bits) of memory. This allows an
int to hold numbers in the range from 2,147,483,648 to
2,147,483,647.
Type int occupies only 2 bytes in 16-bit systems such as MS-DOS
and earlier versions of Windows.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
6. Integer Variables
34
Chapter 2: C++ Programming Basics
There are several numerical integer types besides type int.
The two most common types are long and short. We noted
that the size of type int is system dependent. In contrast,
types long and short have fixed sizes no matter what system
is used.
Type long always occupies four bytes. Thus it has range,
from 2,147,483,648 to 2,147,483,647.
Type short always occupies two bytes. Thus it has range,
from 32,768 to 32,767.
If you want to create a constant of type long, use the letter L
following the numerical value, as in: long var = 7678L;
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
6. Integer Variables
35
Chapter 2: C++ Programming Basics
#include<iostream>
using namespace std;
int main( )
{
int var1;
int var2;
var1 = 20;
var2 = var1 + 10;
cout<<"var1+10 is ";
cout<<var2<<endl;
system("pause");
return 0;
}
Ahmed Mohamed Sayed Ahmed - Computer lecturer
//define var1
//define var2
//assign value to var1
//assign value to var2
//output text
//output value of var2
Output:
var1+10 is 30
Press any key to continue
Thursday, November 22, 2012
6. Integer Variables
36
Chapter 2: C++ Programming Basics
The statement, int var1; ,is called declaration.
You must declare a variable before using it.
However, you can place variable declarations anywhere in
a program.
Its not necessary to declare variables before the first
executable statement (as was necessary in C).
However, its probably more readable if commonly-used
variables are located at the beginning of the program.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
6. Integer Variables
37
Chapter 2: C++ Programming Basics
Output Variations
The statement cout<<"var1+10 is "; displays a string constant.
The next statement cout<<var2<<endl; displays the value of
the variable var2.
The output of the program is var1+10 is 30
As you can see, the output of the two cout statements
appears on the same line on the output screen. No linefeed
is inserted automatically. If you want to start on a new line,
you must insert a linefeed yourself.
cout<<"var1+10 is \n";
cout<<"var1+10 is "<<endl;
or
cout<<var2<<endl;
Ahmed Mohamed Sayed Ahmed - Computer lecturer
cout<<var2<<endl;
Thursday, November 22, 2012
7. Character Variables
38
Chapter 2: C++ Programming Basics
Type char stores integers that range in value from 128 to 127.
Variables of this type occupy only 1 byte (eight bits) of memory.
Character variables are much more commonly used to store
ASCII characters.
The ASCII character set is a way of representing characters such
as a, B, $, 3, and so on, as numbers.
Character constants use single quotation marks around a
character, like a and b. (Note that this differs from string
constants, which use double quotation marks).
When the C++ compiler encounters such a character constant, it
translates it into the corresponding ASCII code. The constant a
appearing in a program, for example, will be translated into 97.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
ASCII Chart
39
Chapter 2: C++ Programming Basics
ASCII
Chart
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
ASCII Chart
40
Chapter 2: C++ Programming Basics
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
ASCII Chart
41
Chapter 2: C++ Programming Basics
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
7. Character Variables
42
Chapter 2: C++ Programming Basics
// charvars.cpp: demonstrates character variables
#include<iostream>
using namespace std;
int main( )
{
char ch1 = 'A';
char ch2 = '\t';
cout<<ch1;
cout<<ch2;
ch1 = 'B';
cout<<ch1;
cout<<'\n';
return 0;
}
Ahmed Mohamed Sayed Ahmed - Computer lecturer
//for cout, etc.
//define char variable as character
//define char variable as tab
//display character
//display character
//set char variable to char constant
//display character
//display newline character
Output:
A
B
Press any key to continue
Thursday, November 22, 2012
7. Character Variables
43
Chapter 2: C++ Programming Basics
Escape Sequences
The character constant \t is an example of an escape sequence.
The name reflects the fact that the backslash causes an escape
from the normal way characters are interpreted.
Escape Sequence
Character
\n
Newline
\t
Tab
\'
Single quotation mark
\"
Double quotation marks
\\
Backslash
\ xdd
Hexadecimal notation
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
7. Character Variables
44
Chapter 2: C++ Programming Basics
Sometimes you need to represent a character constant that
doesnt appear on the keyboard, such as the graphics
characters above ASCII code 127.
To do this, you can use the \xdd representation, where each
d stands for a hexadecimal digit.
If you want to print a solid rectangle, for example, youll
find such a character listed as decimal number 178, which is
hexadecimal number B2 in the ASCII table. This character
would be represented by the character constant \xB2.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
8. Input with cin
45
Chapter 2: C++ Programming Basics
// fahren.cpp
// demonstrates cin, newline
#include<iostream>
using namespace std;
int main( )
{
int ftemp;
//for temperature in fahrenheit
cout<<"Enter temperature in fahrenheit: ";
cin>>ftemp;
int ctemp = (ftemp-32) * 5 / 9;
cout<<"Equivalent in Celsius is: "<<ctemp<<'\n';
return 0;
Output:
}
Enter temperature in fahrenheit: 212
Equivalent in Celsius is: 100
Press any key to continue
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
8. Input with cin
46
Chapter 2: C++ Programming Basics
The statement cin>>ftemp; causes the program to wait for
the user to type in a number.
The resulting number is placed in the variable ftemp.
The keyword cin (pronounced C in) is an object,
predefined in C++ to correspond to the standard input
stream.
This stream represents data coming from the keyboard.
The >> is the extraction or get from operator. It takes the
value from the stream object on its left and places it in the
variable on its right.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
8. Input with cin
47
Chapter 2: C++ Programming Basics
Expressions
Any arrangement of variables, constants, and operators that
specifies a computation is called an expression.
Thus, alpha+12 and (alpha-37)*beta/2 are expressions.
Precedence
Any Arithmetic operation proceeds according to an
established precedence of operations. Thus, Precedence is
the order in which operators are evaluated.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
Precedence Summary
48
Chapter 2: C++ Programming Basics
#include<iostream>
using namespace std;
int main( )
{
int a=4, b=6, c=3, d, e, f, g;
d = a + b * c;
e = (a + b) * c;
f = a * b / c;
g = a * (b / c);
cout<<"d = "<<d<<'\t';
cout<<"e = "<<e<<'\n';
cout<<"f = "<<f<<'\t';
cout<<"g = "<<g<<'\n';
return 0;
}
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Output:
d = 14 e = 30
f=8 g=8
Press any key to continue
Thursday, November 22, 2012
Precedence Summary
49
Chapter 2: C++ Programming Basics
The operators higher on the list have higher precedence
than those lower down.
Operators with higher precedence are evaluated before
those with lower precedence.
Operators on the same row have equal precedence.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
9. Floating Point Types
50
Chapter 2: C++ Programming Basics
Floating-point variables represent numbers with a decimal
place like 3.1415927, 0.0000625, and 10.2.
They have both an integer part, to the left of the decimal
point, and a fractional part, to the right.
Floating-point variables represent what mathematicians call
real numbers, which are used for measurable quantities such
as distance, area, and temperature. They typically have a
fractional part.
There are three kinds of floating-point variables in C++:
type float, type double, and type long double.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
9. Floating Point Types
51
Chapter 2: C++ Programming Basics
Type float
38
Type float stores numbers in the range of about 3.4x10
to 3.4x1038, with a precision of seven digits. It occupies 4
bytes in memory.
Type double
The larger floating point types, double, is similar to float
except that it requires more memory space and provide a
wider range of values and more precision.
Type double requires 8 bytes of storage and handles
numbers in the range from 1.7x10308 to 1.7x10308 with a
precision of 15 digits.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
9. Floating Point Types
52
Chapter 2: C++ Programming Basics
//circarea.cpp
//demonstrates floating point variables
#include<iostream>
//for cout, etc.
using namespace std;
int main( )
{
float rad;
//variable of type float
const float PI = 3.14159F;
//type const float
cout<<"Enter radius of circle: ";
//prompt
cin>>rad;
//get radius
float area = PI * rad * rad;
//find area
cout<<"Area is "<<area<<endl;
//display answer
return 0;
Output:
}
Enter radius of circle: 0.5
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Area is 0.785398
Press any key to
continue
22, 2012
Thursday,
November
9. Floating Point Types
53
Chapter 2: C++ Programming Basics
Exponential Notation
You can write floating-point constants using exponential notation.
Exponential notation is a way of writing large numbers without
having to write out a lot of zeros.
For example, 1,000,000,000 can be written as 1.0E9 in
exponential notation. Similarly, 1234.56 would be written
1.23456E3. (This is the same as 1.23456 *103).
The number following the E is called the exponent. It indicates
how many places the decimal point must be moved to change the
number to ordinary decimal notation.
The exponent can be positive or negative. The exponential
number 6.35239E5 is equivalent to 0.0000635239 in decimal
notation. This is the same as 6.35239 *105.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
9. Floating Point Types
54
Chapter 2: C++ Programming Basics
The const Qualifier
const float PI = 3.14159F;
The keyword const (for constant) precedes the data type of a
variable. It specifies that the value of a variable will not change
throughout the program.
Any attempt to alter the value of a variable defined with this
qualifier will elicit an error message from the compiler.
The #define Directive
The line #define PI 3.14159 appearing at the beginning of your
program specifies that the identifier PI will be replaced by the
text 3.14159 throughout the program.
However, you cant specify the data type of the constant using
#define.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
10. Type bool
55
Chapter 2: C++ Programming Basics
Variables of type bool can have only two possible values:
true and false.
In theory a bool type requires only one bit (not byte) of
storage, but in practice compilers often store them as bytes
because a byte can be quickly accessed, while an individual
bit must be extracted from a byte, which requires additional
time.
As well see, type bool is most commonly used to hold the
results of comparisons.
The true/false values are often called Boolean values.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
11. The setw Manipulator
56
Chapter 2: C++ Programming Basics
You can think of each value displayed by cout as occupying a
field: an imaginary box with a certain width.
The default field is just wide enough to hold the value. That is, the
integer 567 will occupy a field three characters wide, and the
string pajamas will occupy a field seven characters wide.
The setw manipulator causes the number (or string) that follows it
in the stream to be printed within a field n characters wide,
where n is the argument to setw(n).
The declarations for the manipulators (except endl) are not in the
usual iostream header file, but in a separate header file called
iomanip. When you use these manipulators you must #include this
header file in your program.
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
11. The setw Manipulator
57
Chapter 2: C++ Programming Basics
// width1.cpp
// demonstrates need for setw manipulator
#include<iostream>
using namespace std;
int main( )
{
long sd1=83, sd2=78, sd3=91;
cout<<"Name "<<"Degree"<<endl;
cout<<"Ahmed "<<sd1<<endl;
cout<<"Ali "<<sd2<<endl;
cout<<"Mohamed "<<sd3<<endl;
return 0;
}
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Output:
Name Degree
Ahmed 83
Ali 78
Mohamed 91
Press any key to continue
Thursday, November 22, 2012
11. The setw Manipulator
58
Chapter 2: C++ Programming Basics
// width1.cpp
// demonstrates need for setw manipulator
Output:
NAME DEGREE
Ahmed
83
Ali
78
Mohamed
91
Press any key to continue
#include<iostream>
#include<iomanip>
// for setw
using namespace std;
int main( )
{
long sd1=83, sd2=78, sd3=91;
cout<<setw(8)<<"NAME"<<setw(10)<<"DEGREE"<<endl;
cout<<setw(8)<<"Ahmed"<<setw(10)<<sd1<<endl;
cout<<setw(8)<<"Ali"<<setw(10)<<sd2<<endl;
cout<<setw(8)<<"Mohamed"<<setw(10)<<sd3<<endl;
return 0;
}
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
11. The setw Manipulator
59
Chapter 2: C++ Programming Basics
Output:
#include<iostream>
*****NAME**DEGREE
#include<iomanip>
// for setw
****Ahmed*******83
using namespace std;
********Ali*******78
int main( )
*Mohamed *******91
{
Press any key to continue
long sd1=83, sd2=78, sd3=91;
cout<<setw(8)<<setfill('*')<<"NAME;
cout<<setw(10)<<setfill('*')<<"DEGREE"<<endl;
cout<<setw(8)<<setfill('*')<<"Ahmed";
cout<<setw(10)<<setfill('*')<<sd1<<endl;
cout<<setw(8)<<setfill('*')<<"Ali";
cout<<setw(10)<<setfill('*')<<sd2<<endl;
cout<<setw(8)<<setfill('*')<<"Mohamed";
cout<<setw(10)<<setfill('*')<<sd3<<endl;
return 0;
}
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
11. The setw Manipulator
60
Chapter 2: C++ Programming Basics
Output:
#include<iostream>
NAME
DEGREE
#include<iomanip>
// for setw
Ahmed
83
using namespace std;
Ali
78
int main( )
Mohamed 91
{
Press any key to continue
long sd1=83, sd2=78, sd3=91;
cout<<setw(8)<<setiosflags(ios::left)<<"NAME;
cout<<setw(10)<<setiosflags(ios::left)<<"DEGREE"<<endl;
cout<<setw(8)<<setiosflags(ios::left)<<"Ahmed";
cout<<setw(10)<<setiosflags(ios::left)<<sd1<<endl;
cout<<setw(8)<<setiosflags(ios::left)<<"Ali";
cout<<setw(10)<<setiosflags(ios::left)<<sd2<<endl;
cout<<setw(8)<<setiosflags(ios::left)<<"Mohamed";
cout<<setw(10)<<setiosflags(ios::left)<<sd3<<endl;
return 0;
}
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
12. Variable Type Summary
61
Chapter 2: C++ Programming Basics
Ahmed Mohamed Sayed Ahmed - Computer lecturer
Thursday, November 22, 2012
62
Thanks for
Listening