You are on page 1of 55

Structure of a program

The best way to learn a programming language is by writing programs. Typically, the first program beginners write is a program called
"Hello World", which simply prints "Hello World" to your computer screen. Although it is very simple, it contains all the fundamental
components C++ programs have:
1 // my first program in C++
2 #include <iostream>
3
4 int main()
5{
6 std::cout << "Hello World!";
7}

Hello World!

Edit
&
Run

The left panel above shows the C++ code for this program. The right panel shows the result when the program is executed by a
computer. The grey numbers to the left of the panels are line numbers to make discussing programs and researching errors easier. They
are not part of the program.
Let's examine this program line by line:
Line 1: // my first program in C++
Two slash signs indicate that the rest of the line is a comment inserted by the programmer but which has no effect on the
behavior of the program. Programmers use them to include short explanations or observations concerning the code or program.
In this case, it is a brief introductory description of the program.
Line 2: #include <iostream>
Lines beginning with a hash sign (#) are directives read and interpreted by what is known as the preprocessor. They are special
lines interpreted before the compilation of the program itself begins. In this case, the directive#include <iostream>, instructs
the preprocessor to include a section of standard C++ code, known as header iostream, that allows to perform standard input
and output operations, such as writing the output of this program (Hello World) to the screen.
Line 3: A blank line.
Blank lines have no effect on a program. They simply improve readability of the code.

Line 4: int main ()


This line initiates the declaration of a function. Essentially, a function is a group of code statements which are given a name: in
this case, this gives the name "main" to the group of code statements that follow. Functions will be discussed in detail in a later
chapter, but essentially, their definition is introduced with a succession of a type (int), a name (main) and a pair of parentheses
(()), optionally including parameters.
The function named main is a special function in all C++ programs; it is the function called when the program is run. The
execution of all C++ programs begins with the main function, regardless of where the function is actually located within the
code.
Lines 5 and 7: { and }
The open brace ({) at line 5 indicates the beginning of main's function definition, and the closing brace (}) at line 7, indicates
its end. Everything between these braces is the function's body that defines what happens when main is called. All functions
use braces to indicate the beginning and end of their definitions.
Line 6: std::cout << "Hello World!";
This line is a C++ statement. A statement is an expression that can actually produce some effect. It is the meat of a program,
specifying its actual behavior. Statements are executed in the same order that they appear within a function's body.
This statement has three parts: First, std::cout, which identifies the standard character output device (usually, this is the
computer screen). Second, the insertion operator (<<), which indicates that what follows is inserted intostd::cout. Finally, a
sentence within quotes ("Hello world!"), is the content inserted into the standard output.
Notice that the statement ends with a semicolon (;). This character marks the end of the statement, just as the period ends a
sentence in English. All C++ statements must end with a semicolon character. One of the most common syntax errors in C++ is
forgetting to end a statement with a semicolon.
You may have noticed that not all the lines of this program perform actions when the code is executed. There is a line containing a
comment (beginning with //). There is a line with a directive for the preprocessor (beginning with #). There is a line that defines a
function (in this case, the main function). And, finally, a line with a statements ending with a semicolon (the insertion into cout),
which was within the block delimited by the braces ( { } ) of the main function.

The program has been structured in different lines and properly indented, in order to make it easier to understand for the humans
reading it. But C++ does not have strict rules on indentation or on how to split instructions in different lines. For example, instead of
Edit & Run

1 int main ()
2{
3 std::cout << " Hello World!";
4}

We could have written:


Edit & Run

int main () { std::cout << "Hello World!"; }

all in a single line, and this would have had exactly the same meaning as the preceding code.
In C++, the separation between statements is specified with an ending semicolon (;), with the separation into different lines not
mattering at all for this purpose. Many statements can be written in a single line, or each statement can be in its own line. The division
of code in different lines serves only to make it more legible and schematic for the humans that may read it, but has no effect on the
actual behavior of the program.
Now, let's add an additional statement to our first program:
1 // my second program in C++
2 #include <iostream>
3
4 int main ()
5{
6 std::cout << "Hello World! ";
7 std::cout << "I'm a C++ program";
8}

Hello World! I'm a C++ program

Edit
&
Run

In this case, the program performed two insertions into std::cout in two different statements. Once again, the separation in different
lines of code simply gives greater readability to the program, since main could have been perfectly valid defined in this way:

Edit & Run

int main () { std::cout << " Hello World! "; std::cout << " I'm a C++ program "; }

The source code could have also been divided into more code lines instead:
1 int main ()
2{
3 std::cout <<
4
"Hello World!";
5 std::cout
6
<< "I'm a C++ program";
7}

Edit & Run

And the result would again have been exactly the same as in the previous examples.
Preprocessor directives (those that begin by #) are out of this general rule since they are not statements. They are lines read and
processed by the preprocessor before proper compilation begins. Preprocessor directives must be specified in their own line and,
because they are not statements, do not have to end with a semicolon (;).

Comments
As noted above, comments do not affect the operation of the program; however, they provide an important tool to document directly
within the source code what the program does and how it operates.
C++ supports two ways of commenting code:
1 // line comment
2 /* block comment */

The first of them, known as line comment, discards everything from where the pair of slash signs (//) are found up to the end of that
same line. The second one, known as block comment, discards everything between the /* characters and the first appearance of

the */ characters, with the possibility of including multiple lines.


Let's add comments to our second program:
1 /* my second program in C++
Hello World! I'm a C++ program
2
with more comments */
3
4 #include <iostream>
5
6 int main ()
7{
8 std::cout << "Hello World! ";
// prints Hello
9 World!
10 std::cout << "I'm a C++ program"; // prints I'm a
C++ program
}

Edit
&
Run

If comments are included within the source code of a program without using the comment characters combinations //,/* or */, the
compiler takes them as if they were C++ expressions, most likely causing the compilation to fail with one, or several, error messages.

Using namespace std


If you have seen C++ code before, you may have seen cout being used instead of std::cout. Both name the same object: the first
one uses its unqualified name (cout), while the second qualifies it directly within the namespace std (asstd::cout).
is part of the standard library, and all the elements in the standard C++ library are declared within what is a called anamespace:
the namespace std.
cout

In order to refer to the elements in the std namespace a program shall either qualify each and every use of elements of the library (as
we have done by prefixing cout with std::), or introduce visibility of its components. The most typical way to introduce visibility of
these components is by means of using declarations:
using namespace std;

The above declaration allows all elements in the std namespace to be accessed in an unqualified manner (without thestd:: prefix).
With this in mind, the last example can be rewritten to make unqualified uses of cout as:
1 // my second program in C++
2 #include <iostream>
3 using namespace std;
4
5 int main ()
6{
7 cout << "Hello World! ";
8 cout << "I'm a C++ program";
9}

Hello World! I'm a C++ program

Edit
&
Run

Both ways of accessing the elements of the std namespace (explicit qualification and using declarations) are valid in C++ and produce
the exact same behavior. For simplicity, and to improve readability, the examples in these tutorials will more often use this latter
approach with using declarations, although note that explicit qualification is the only way to guarantee that name collisions never
happen.
Namespaces are explained in more detail in a later chapter.

C++ Data Types

While doing programming in any programming language, you need to use various variables to store
various information. Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
You may like to store information of various data types like character, wide character, integer, floating
point, double floating point, boolean etc. Based on the data type of a variable, the operating system
allocates memory and decides what can be stored in the reserved memory.

Primitive Built-in Types:


C++ offer the programmer a rich assortment of built-in as well as user defined data types. Following
table lists down seven basic C++ data types:
Type

Keyword

Boolean

bool

Character

char

Integer

int

Floating point

float

Double floating point

double

Valueless

void

Wide character

wchar_t

Several of the basic types can be modified using one or more of these type modifiers:

signed

unsigned

short

long

The following table shows the variable type, how much memory it takes to store the value in memory,
and what is maximum and minimum value which can be stored in such type of variables.
Type

Typical Bit Width

Typical Range

char

1byte

-128 to 127 or 0 to 255

unsigned char

1byte

0 to 255

signed char

1byte

-128 to 127

int

4bytes

-2147483648 to 2147483647

unsigned int

4bytes

0 to 4294967295

signed int

4bytes

-2147483648 to 2147483647

short int

2bytes

-32768 to 32767

unsigned short int

2bytes

0 to 65,535

signed short int

2bytes

-32768 to 32767

long int

4bytes

-2,147,483,648 to 2,147,483,647

signed long int

4bytes

-2,147,483,648 to 2,147,483,647

unsigned long int

4bytes

0 to 4,294,967,295

float

4bytes

+/- 3.4e +/- 38 (~7 digits)

double

8bytes

+/- 1.7e +/- 308 (~15 digits)

long double

8bytes

+/- 1.7e +/- 308 (~15 digits)

wchar_t

2 or 4 bytes

1 wide character

The sizes of variables might be different from those shown in the above table, depending on the compiler
and the computer you are using.
Following is the example, which will produce correct size of various data types on your computer.
#include <iostream>
using namespace std;

int main()
{
cout << "Size of char : " << sizeof(char) << endl;
cout << "Size of int : " << sizeof(int) << endl;
cout << "Size of short int : " << sizeof(short int) << endl;

cout << "Size of long int : " << sizeof(long int) << endl;
cout << "Size of float : " << sizeof(float) << endl;
cout << "Size of double : " << sizeof(double) << endl;
cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
return 0;
}

This example uses endl, which inserts a new-line character after every line and << operator is being
used to pass multiple values out to the screen. We are also using sizeof() operator to get size of various
data types.
When the above code is compiled and executed, it produces the following result which can vary from
machine to machine:
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 8
Size of float : 4
Size of double : 8
Size of wchar_t : 4

typedef Declarations:
You can create a new name for an existing type using typedef. Following is the simple syntax to define a
new type using typedef:
typedef type newname;

For example, the following tells the compiler that feet is another name for int:
typedef int feet;

Now, the following declaration is perfectly legal and creates an integer variable called distance:
feet distance;

Enumerated Types:
An enumerated type declares an optional type name and a set of zero or more identifiers that can be
used as values of the type. Each enumerator is a constant whose type is the enumeration.
To create an enumeration requires the use of the keyword enum. The general form of an enumeration
type is:
enum enum-name { list of names } var-list;

Here, the enum-name is the enumeration's type name. The list of names is comma separated.

For example, the following code defines an enumeration of colors called colors and the variable c of type
color. Finally, c is assigned the value "blue".
enum color { red, green, blue } c;
c = blue;

By default, the value of the first name is 0, the second name has the value 1, the third has the value 2,
and so on. But you can give a name a specific value by adding an initializer. For example, in the following
enumeration, green will have the value 5.
enum color { red, green=5, blue };

Here, blue will have a value of 6 because each name will be one greater than the one that precedes it.

Operators in C++

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
C++ is rich in built-in operators and provides the following types of operators:

Arithmetic Operators

Relational Operators

Logical Operators

Bitwise Operators

Assignment Operators

Misc Operators

This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other operators one
by one.

Arithmetic Operators:
There are following arithmetic operators supported by C++ language:
Assume variable A holds 10 and variable B holds 20, then:
Show Examples
Operato
r

Description

Example

Adds two operands

A + B will give 30

Subtracts second operand from the first

A - B will give -10

Multiplies both operands

A * B will give 200

Divides numerator by de-numerator

B / A will give 2

Modulus Operator and remainder of after


an integer division

B % A will give 0

++

Increment operator, increases integer


value by one

A++ will give 11

--

Decrement operator, decreases integer


value by one

A-- will give 9

Relational Operators:
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then:
Show Examples

Pp[Operato
r

Description

Example

==

Checks if the values of two operands


are equal or not, if yes then condition
becomes true.

(A == B) is not true.

!=

Checks if the values of two operands


are equal or not, if values are not equal
then condition becomes true.

(A != B) is true.

>

Checks if the value of left operand is


greater than the value of right
operand, if yes then condition becomes
true.

(A > B) is not true.

<

Checks if the value of left operand is


less than the value of right operand, if
yes then condition becomes true.

(A < B) is true.

>=

Checks if the value of left operand is


greater than or equal to the value of
right operand, if yes then condition
becomes true.

(A >= B) is not true.

<=

Checks if the value of left operand is

(A <= B) is true.

less than or equal to the value of right


operand, if yes then condition becomes
true.

Logical Operators:
There are following logical operators supported by C++ language
Assume variable A holds 1 and variable B holds 0, then:
Show Examples
Operato
r

Description

Example

&&

Called Logical AND operator. If both the


operands are non-zero, then condition
becomes true.

(A && B) is false.

||

Called Logical OR Operator. If any of the


two operands is non-zero, then condition
becomes true.

(A || B) is true.

Called Logical NOT Operator. Use to


reverses the logical state of its operand.
If a condition is true, then Logical NOT

!(A && B) is true.

operator will make false.

Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are as
follows:
p

p&q

p|q

p^q

Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------

A&B = 0000 1100


A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume variable A
holds 60 and variable B holds 13, then:
Show Examples
Operato
r

Description

Example

&

Binary AND Operator copies a bit to the


result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

Binary OR Operator copies a bit if it


exists in either operand.

(A | B) will give 61 which is 0011 1101

Binary XOR Operator copies the bit if it is


set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

Binary Ones Complement Operator is

(~A ) will give -61 which is 1100 0011 in

unary and has the effect of 'flipping' bits.

2's complement form due to a signed


binary number.

<<

Binary Left Shift Operator. The left


operands value is moved left by the
number of bits specified by the right
operand.

A << 2 will give 240 which is 1111 0000

>>

Binary Right Shift Operator. The left


operands value is moved right by the
number of bits specified by the right
operand.

A >> 2 will give 15 which is 0000 1111

Assignment Operators:
There are following assignment operators supported by C++ language:
Show Examples
Operato
r

Description

Example

Simple assignment operator, Assigns


values from right side operands to left
side operand

C = A + B will assign value of A + B into


C

+=

Add AND assignment operator, It adds


right operand to the left operand and
assign the result to left operand

C += A is equivalent to C = C + A

-=

Subtract AND assignment operator, It


subtracts right operand from the left
operand and assign the result to left
operand

C -= A is equivalent to C = C - A

*=

Multiply AND assignment operator, It


multiplies right operand with the left
operand and assign the result to left
operand

C *= A is equivalent to C = C * A

/=

Divide AND assignment operator, It


divides left operand with the right
operand and assign the result to left
operand

C /= A is equivalent to C = C / A

%=

Modulus AND assignment operator, It


takes modulus using two operands and
assign the result to left operand

C %= A is equivalent to C = C % A

<<=

Left shift AND assignment operator

C <<= 2 is same as C = C << 2

>>=

Right shift AND assignment operator

C >>= 2 is same as C = C >> 2

&=

Bitwise AND assignment operator

C &= 2 is same as C = C & 2

^=

bitwise exclusive OR and assignment


operator

C ^= 2 is same as C = C ^ 2

|=

bitwise inclusive OR and assignment


operator

C |= 2 is same as C = C | 2

Misc Operators
There are few other operators supported by C++ Language.
Operator

Description

sizeof

sizeof operator returns the size of a variable. For example,


sizeof(a), where a is integer, will return 4.

Condition ? X : Y

Conditional operator. If Condition is true ? then it returns value


X : otherwise value Y

Comma operator causes a sequence of operations to be


performed. The value of the entire comma expression is the value

of the last expression of the comma-separated list.

. (dot) and -> (arrow)

Member operators are used to reference individual members of


classes, structures, and unions.

Cast

Casting operators convert one data type to another. For example,


int(2.2000) would return 2.

&

Pointer operator & returns the address of an variable. For


example &a; will give actual address of the variable.

Pointer operator * is pointer to a variable. For example *var; will


pointer to a variable var.

Operators Precedence in C++:


Operator precedence determines the grouping of terms in an expression. This affects how an expression
is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator:
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom. Within an expression, higher precedence operators will be evaluated first.

Show Examples
Category

Operator

Associativity

Postfix

() [] -> . ++ - -

Left to right

Unary

+ - ! ~ ++ - - (type)* & sizeof

Right to left

Multiplicative

*/%

Left to right

Additive

+-

Left to right

Shift

<< >>

Left to right

Relational

< <= > >=

Left to right

Equality

== !=

Left to right

Bitwise AND

&

Left to right

Bitwise XOR

Left to right

Bitwise OR

Left to right

Logical AND

&&

Left to right

Logical OR

||

Left to right

Conditional

?:

Right to left

Assignment

= += -= *= /= %=>>= <<= &= ^= |=

Right to left

Comma

Left to right

C++ Basic Input/Output

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in
subsequent chapters. This chapter will discuss very basic and most common I/O operations required for
C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a
disk drive, or a network connection etc. to main memory, this is called input operation and if bytes flow
from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc,
this is called output operation.

I/O Library Header Files:


There are following header files important to C++ programs:
Header File

Function and Description

<iostream>

This file defines the cin, cout, cerr and clog objects, which correspond to
the standard input stream, the standard output stream, the un-buffered
standard error stream and the buffered standard error stream, respectively.

<iomanip>

This file declares services useful for performing formatted I/O with so-called
parameterized stream manipulators, such as setw and setprecision.

<fstream>

This file declares services for user-controlled file processing. We will discuss
about it in detail in File and Stream related chapter.

The standard output stream (cout):


The predefined object cout is an instance of ostream class. The cout object is said to be "connected to"
the standard output device, which usually is the display screen. The cout is used in conjunction with the
stream insertion operator, which is written as << which are two less than signs as shown in the following
example.
#include <iostream>

using namespace std;

int main( )
{
char str[] = "Hello C++";

cout << "Value of str is : " << str << endl;


}

When the above code is compiled and executed, it produces the following result:
Value of str is : Hello C++

The C++ compiler also determines the data type of variable to be output and selects the appropriate
stream insertion operator to display the value. The << operator is overloaded to output data items of
built-in types integer, float, double, strings and pointer values.
The insertion operator << may be used more than once in a single statement as shown above
and endl is used to add a new-line at the end of the line.

The standard input stream (cin):


The predefined object cin is an instance of istream class. The cin object is said to be attached to the
standard input device, which usually is the keyboard. The cin is used in conjunction with the stream

extraction operator, which is written as >> which are two greater than signs as shown in the following
example.
#include <iostream>

using namespace std;

int main( )
{
char name[50];

cout << "Please enter your name: ";


cin >> name;
cout << "Your name is: " << name << endl;

When the above code is compiled and executed, it will prompt you to enter a name. You enter a value
and then hit enter to see the result something as follows:
Please enter your name: cplusplus
Your name is: cplusplus

The C++ compiler also determines the data type of the entered value and selects the appropriate stream
extraction operator to extract the value and store it in the given variables.

The stream extraction operator >> may be used more than once in a single statement. To request more
than one datum you can use the following:
cin >> name >> age;

This will be equivalent to the following two statements:


cin >> name;
cin >> age;

The standard error stream (cerr):


The predefined object cerr is an instance of ostream class. The cerr object is said to be attached to the
standard error device, which is also a display screen but the object cerr is un-buffered and each stream
insertion to cerr causes its output to appear immediately.
The cerr is also used in conjunction with the stream insertion operator as shown in the following
example.
#include <iostream>

using namespace std;

int main( )
{
char str[] = "Unable to read....";

cerr << "Error message : " << str << endl;


}

When the above code is compiled and executed, it produces the following result:
Error message : Unable to read....

The standard log stream (clog):


The predefined object clog is an instance of ostream class. The clog object is said to be attached to the
standard error device, which is also a display screen but the object clog is buffered. This means that
each insertion to clog could cause its output to be held in a buffer until the buffer is filled or until the
buffer is flushed.
The clog is also used in conjunction with the stream insertion operator as shown in the following
example.
#include <iostream>

using namespace std;

int main( )
{
char str[] = "Unable to read....";

clog << "Error message : " << str << endl;


}

When the above code is compiled and executed, it produces the following result:
Error message : Unable to read....

You would not be able to see any difference in cout, cerr and clog with these small examples, but while
writing and executing big programs then difference becomes obvious. So this is good practice to display
error messages using cerr stream and while displaying other log messages then clog should be used.

Escape Sequence in C++ Programming with Examples

Escape sequences in C++ Programming are character combinations which comprise a backslash (\) followed by some
character. They give results such as getting to the next line or a TAB space. They are called escape sequences since the
backslash causes an escape from the normal way characters are interpreted by the C++ compiler.
Lets begin with a simple C++ program that display a message on screen with no escape sequence character used.

C++ program to display message

(adsbygoogle = window.adsbygoogle || []).push({});

#include<iostream.h>
#include<conio.h>

Void main()
{
cout<<"Escape Sequence";
getch();
}

Question: How will you print your message Escape Sequence in C++ Programming divided in two different lines?

Source code | more options -->

#include<iostream.h>
#include<conio.h>

Void main()
{
cout<<"Escape Sequence ";
cout<<"in C++ Programming.";
getch();
}

Program Output:
Escape Sequence in C++ Programming.
The above program prints the complete string message in just one line instead of two. The reason is that you didnt gave
any instruction to print nextcout string message in the next line.
Take a look at the following program to know how to print anything in a new line using C++ Escape Sequence Character.

Use of Escape sequence in C++ program

#include<iostream.h>

#include<conio.h>

Void main()
{
cout<<"First Name\nLast Name";
getch();
}

Notice that? \n between the double quotes. Its an escape sequence in C++ used to display the output string message in a
new line. Both the programs have identical output but the second program saves your time and effort, thats what
the programming is known for.
So are you able to guess the output of the following program? Note that I have used more than one C++ escape sequence
character.

Use of escape sequence character twice

#include<iostream.h>
#include<conio.h>

Void main()
{

cout<<"Himanshu\nNegi\nLoves C++";
}

The output is shown below:


Himanshu
Negi
Loves C++

Significance of Escape sequence in C++ Programming?


What is the real importance and of escape sequences in a programming language? Now think about the situation
when you wish to display a double quotation () mark on the screen? No, you cant put it in cout statement as it will just
terminate the cout message and nothing else happen other than getting an Error on Screen by compiler.
Example: cout<<Quotaion Symbol inserted here;

// Invalid

There is only way, use escape sequence character. The following C++ program puts some light on the situation.

Important use of Escape Sequence in C++

#include<iostream.h>
#include<conio.h>

Void main()

{
cout<<"\" Displayed";
}

NOTE: If you will simply put a quotation mark in between cout quotes then the compiler will get confused. Your quotation
mark between quotes will be seen as an end of cout message by the compiler and the actual quotation mark () will be
seen as an extra.

List of Some C++ Escape Sequence Characters:


This is the list of some known Escape Sequence in C++. Dont forget to try them. Do some experiment and show your
creativity.
\a Bell(bep) \b Backspace \f Formfeed \n New line \r Carriage Return \t Horizontal Tab \\ Backslash \ Single
Quotation Mark \ Double Quatation Mark

Escape sequence in C++ Programming

Output Formatting

Formatting program output is an essential part of any serious application. Surprisingly, most
C++ textbooks don't give a full treatment of output formatting. The purpose of this section is
to describe the full range of formatting abilities available in C++.
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are
placed on the output stream. Most of the standard manipulators are found in <iostream> and so are included
automatically. The standard C++ manipulators are not keywords in the language, just like cin and cout, but it is often
convenient to think of them as a permanent part of the language.
The standard C++ output manipulators are:
endl

- places a new line character on the output stream. This is identical to placing
output stream.

'\n'

on the

#include<iostream>
using std::cout;
using std::endl;
int main()
{
cout << "Hello world 1" << endl;
cout << "Hello world 2\n";
}

return 0;

produces
Hello world 1
Hello world 2
flush

- flushes the output buffer to its final destination.


Some explanation is in order here. For efficiency reasons, most output is not sent directly to the output device at
the time a program uses acout statement. Rather it is collected in an output buffer in the system memory.
Periodically, the collected contents of the buffer are flushed to the output device in one large block. This is much
faster than sending the output one character at a time. This flushing happens automatically when the buffer
contents get too large.
The output buffer is also flushed before an input statement is executed. This is because the output may be a
prompt, and a prompt should appear on the screen in full before any input is accepted.
The output buffer is also flushed when the stream is closed at the end of the program.
In short, the output buffer and its flushing mechanism is largely transparent to the user. The
rarely needed.

flush

manipulator is

One exception to this is in using printing statements for debugging. When a program crashes, the output buffer
may or may not make it to the output device when the program terminates. Consequently, if print statements are
used to locate where the crash occurs, misleading results may be obtained. Using the flush operator after every
output will help prevent this problem (but is not guaranteed to work every time).
A better solution to this problem is to use the output stream cerr for error output. This stream is also defined
in <iostream> and is an output stream of type ostream. It works just like cout except that all output is
automatically flushed.
Field width
A very useful thing to do in a program is output numbers and strings in fields of fixed
width. This is crucial for reports.
setw()

- Adjusts the field with for the item about to be printed.


Important Point
The setw() manipulator only affects the next value to be printed.

The setw() manipulator takes an integer argument which is the minimum field width for the value to be printed.
Important Point
All manipulators that take arguments are defined in the header
file iomanip. This header file must be included to use such

manipulators.
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
int main()
{
// A test of setw()
cout << "*" << -17 << "*" << endl;
cout << "*" << setw(6) << -17 << "*" << endl << endl;
cout << "*" << "Hi there!" << "*" << endl;
cout << "*" << setw(20) << "Hi there!" << "*" << endl;
cout << "*" << setw(3) << "Hi there!" << "*" << endl;
}

return 0;

produces
*-17*
*
-17*
*Hi there!*
*
Hi there!*
*Hi there!*

Note that the values are right justified in their fields. This can be changed. Note also what happens if the value is
too big to fit in the field.
Important Point
The argument given to setw() is a minimum width. If the value

needs more space, the output routines will use as much as is


needed.

This field overflow strategy is different than that used in other programming languages. Some languages will fill
a small field with *'s or #'s. Others will truncate the value. The philosophy for the C++ standard output is that it's
better to have a correct value formatted poorly than to have a nicely formatted error.
Important Point
The default field width is 0.

Justification
Values can be justified in their fields. There are three manipulators for adjusting the
justification: left, right, and internal.
Important Point
The default justification is right justification.

Important Point
All manipulators except setw() are persistent. Their effect
continues until explicitly changed.
left

- left justify all values in their fields.


right

- right justify all values in their fields. This is the default justification value.
#include <iostream>
#include <iomanip>
using
using
using
using
using

std::cout;
std::endl;
std::setw;
std::left;
std::right;

int main()
{
cout << "*" << -17 << "*" << endl;
cout << "*" << setw(6) << -17 << "*" << endl;
cout << left;
cout << "*" << setw(6) << -17 << "*" << endl << endl;
cout
cout
cout
cout
}

<<
<<
<<
<<

"*" << "Hi there!" << "*" << endl;


"*" << setw(20) << "Hi there!" << "*" << endl;
right;
"*" << setw(20) << "Hi there!" << "*" << endl;

return 0;

produces
*-17*
*
-17*
*-17
*
*Hi there!*
*Hi there!
*
*
Hi there!*
internal

- internally justifies numeric values in their fields. Internal justification separates the sign
of a number from its digits. The sign is left justified and the digits are right justified. This

is a useful format in accounting and business programs, but is rarely used in other
applications.
#include <iostream>
#include <iomanip>
using
using
using
using

std::cout;
std::endl;
std::setw;
std::internal;

int main()
{
cout << setw(9) << -3.25 << endl;
cout << internal << setw(9) << -3.25 << endl;
return 0;
}

produces
boolalpha

-3.25
3.25

and

noboolalpha

Boolean values (variables of type bool) are normally printed as 0 for false and 1 for true. It
is sometimes nice to print out these values as words. The boolalpha manipulator will print
out true and false values as true and false respectively. The nobooolalpha manipulator will
return the printed values to 1 and 0.
#include <iostream>
using
using
using
using

std::cout;
std::endl;
std::boolalpha;
std::noboolalpha;

int main()
{
bool bt = true, bf = false;
cout
cout
cout
cout
cout
}

<<
<<
<<
<<
<<

"bt: " << bt << " bf: " << bf << endl;
boolalpha;
"bt: " << bt << " bf: " << bf << endl;
noboolalpha;
"bt: " << bt << " bf: " << bf << endl;

return 0;

produces
bt: 1 bf: 0
bt: true bf: false
bt: 1 bf: 0

A point for advanced users: In a Unix environment changing the default session language will automatically
change the alpha values for true and false so that boolalpha will use the proper words for that language.
showpos

and

noshowpos

This manipulator determines how positive numbers are printed. A negative number is
traditionally printed with a minus sign in front. The lack of a minus sign means a positive
value. However some accounting and scientific applications traditionally place a plus sign
in front of positive numbers just to emphasize the fact that the number is positive. Using
the showpos manipulator makes this happen automatically. Thenoshowpos manipulator returns
the output state to placing nothing in front of positive values.
#include <iostream>
using
using
using
using

std::cout;
std::endl;
std::showpos;
std::noshowpos;

int main()
{
int pos_int = 4, neg_int = -2, zero_int = 0;
float pos_f = 3.5, neg_f = -31.2, zero_f = 0.0;
cout
cout
cout
cout

<<
<<
<<
<<

"pos_int: " << pos_int << " neg_int: " << neg_int;
" zero_int: " << zero_int << endl;
"pos_f: " << pos_f << " neg_f: " << neg_f;
" zero_f: " << zero_f << endl << endl;

cout << showpos;


cout
cout
cout
cout
}

<<
<<
<<
<<

"pos_int: " << pos_int << " neg_int: " << neg_int;
" zero_int: " << zero_int << endl;
"pos_f: " << pos_f << " neg_f: " << neg_f;
" zero_f: " << zero_f << endl << endl;

return 0;

produces
pos_int: 4
pos_f: 3.5
pos_int: +4
pos_f: +3.5

neg_int: -2 zero_int: 0
neg_f: -31.2 zero_f: 0
neg_int: -2 zero_int: +0
neg_f: -31.2 zero_f: +0

Note that zero is considered to be a positive number in this case.


Integer base
Computer science applications occasionally use number systems other than base 10. The most frequently used
number systems (after decimal) are octal (base 8) and hexadecimal (base 16). Octal number systems use the
digits 0 through 7. Hexadecimal systems use the digits 0 through 9 and add the digits A through F to represent in
one digit the values ten through fifteen.

The manipulators dec, oct, and hex change the base that is used to print out integer values.
Important Point
The base used for output formatting is completely independent
from how a value is stored in machine memory. During output, the
bit patterns in memory are converted to character sequences that
are meaningful to human beings.
#include <iostream>
using
using
using
using
using

std::cout;
std::endl;
std::dec;
std::oct;
std::hex;

int main()
{
// These sequences of characters are treated as decimal numbers by
// the compiler and converted to the machine internal format.
long int pos_value = 12345678;
long int neg_value = -87654321;
float value = 2.71828;
cout << "The decimal value 12345678 is printed out as" << endl;
cout << "decimal:
" << pos_value << endl;
cout << "octal:
" << oct << pos_value << endl;
cout << "hexadecimal: " << hex << pos_value << endl << endl;
cout
cout
cout
cout

<<
<<
<<
<<

"The decimal value


"decimal:
" <<
"octal:
" <<
"hexadecimal: " <<

-87654321 is printed out as" << endl;


dec << neg_value << endl;
oct << neg_value << endl;
hex << neg_value << endl << endl;

cout
cout
cout
cout

<<
<<
<<
<<

"The decimal value


"decimal:
" <<
"octal:
" <<
"hexadecimal: " <<

2.71828 is printed out as" << endl;


dec << value << endl;
oct << value << endl;
hex << value << endl << endl;

return 0;
}

produces
The decimal value 12345678 is printed out as
decimal:
12345678
octal:
57060516
hexadecimal: bc614e
The decimal value -87654321 is printed out as
decimal:
-87654321
octal:
37261500117
hexadecimal: fac6804f
The decimal value 2.71828 is printed out as
decimal:
2.71828
octal:
2.71828
hexadecimal: 2.71828

Note that negative integers are not printed as such in octal or hexadecimal. Rather, the internal bit patterns are
interpreted as always being positive values.
Also note that floating point values are always printed out in decimal format.
showbase

and

noshowbase

When a program is printing out integers in decimal, octal, and hex, it can become difficult
to determine at a glance what the real value of a number is. For example, a program
outputs the string of characters ``1234''. Does this represent a decimal 1234, an octal
1234 or a hexadecimal 1234? All are legal but very different internal values.

By tradition in C/C++, any printed integer value that is immediately preceded by a zero is considered to be an
octal value. Any printed integer that is immediately preceded by a ``0x'' is considered to be a hexadecimal value.
For example the output 1234 is likely a decimal value. The output 01234 is considered to be octal and 0x1234 is
considered to be hexadecimal.
By default, these prefixes are not added. The programmer can add them or the showbase manipulator can be used.
This manipulator simply provides an appropriate prefix to octal and hexadecimal values.
The noshowbase manipulator turns off this behavior.
#include <iostream>
using
using
using
using
using
using
using

std::cout;
std::endl;
std::dec;
std::oct;
std::hex;
std::showbase;
std::noshowbase;

int main()
{
long int value =

12345678;

cout << "The decimal value 12345678 is printed out with showbase as" << endl;
cout << showbase;
cout << "decimal:
" << value << endl;
cout << "octal:
" << oct << value << endl;
cout << "hexadecimal: " << hex << value << endl << endl;
cout << "The decimal value 12345678 is printed out without showbase as" << endl;
cout << noshowbase;
cout << "decimal:

" << dec << value << endl;

cout << "octal:


" << oct << value << endl;
cout << "hexadecimal: " << hex << value << endl << endl;
return 0;
}

produces
The decimal value 12345678 is printed out with showbase as
decimal:
12345678
octal:
057060516
hexadecimal: 0xbc614e
The decimal value 12345678 is printed out without showbase as
decimal:
12345678
octal:
57060516
hexadecimal: bc614e
uppercase

and

nouppercase

Numeric output consists largely of numeric digits. But there are a few places where
alphabetic characters make their appearance. These include the 0x prefix for hexadecimal
numbers, the hexadecimal digits a through f, and the e that is used in scientific notation
for large floating point numbers ( 6.02e+23). In some applications, it is important that these
letters appear as uppercase letters instead of lowercase. The uppercase manipulator
enables this behavior. The nouppercase manipulator turns all of these characters back to
lower case.
#include <iostream>
using
using
using
using
using
using
using
using

std::cout;
std::endl;
std::dec;
std::oct;
std::hex;
std::showbase;
std::noshowbase;
std::uppercase;

using std::nouppercase;
int main()
{
long int value = 12345678;
float
value_f = 6020000000.0;
cout
cout
cout
cout

<<
<<
<<
<<

"Some values without the uppercase manipulator" << endl;


showbase << hex;
"hexadecimal: " << value << endl;
"exponential: " << value_f << endl << endl;

cout << uppercase;


cout << "Some values with the uppercase manipulator" << endl;
cout << "hexadecimal: " << value << endl;
cout << "exponential: " << value_f << endl << endl;
}

return 0;

produces
Some values without the uppercase manipulator
hexadecimal: 0xbc614e
exponential: 6.02e+09
Some values with the uppercase manipulator
hexadecimal: 0XBC614E
exponential: 6.02E+09

Floating Point Output

There are 3 floating point formats: general, fixed, and scientific. Fixed format always has a number, decimal
point, and fraction part, no matter how big the number gets, i.e., not scientific notation. 6.02e+17 would be
displayed as 602000000000000000 instead of 6.02e+17.
Scientific format always displays a number in scientific notation. The value of one-fourth would not be displayed
as 0.25, but as 2.5e-01instead.

General format is a mix of fixed and scientific formats. If the number is small enough, fixed format is used. If
the number gets too large, the output switches over to scientific format. General format is the default format for
floating point values.
fixed

and

scientific

The manipulator fixed will set up the output stream for displaying floating point values in fixed format.
The scientific manipulator forces all floating point values to be displayed in scientific notation.
Unfortunately, there is no manipulator to place the output stream back into general format. The author of these
notes considers this to be a design flaw in the standard C++ libraries. There is a way to place the output stream
back into general format, but it's not pretty and requires more explanation than is appropriate here. In short,
here's the magic incantation
cout.unsetf(ios::fixed | ios::scientific);

In order to use this statement, you need a

using

#include <iostream>
using
using
using
using
using

std::cout;
std::endl;
std::scientific;
std::fixed;
std::ios;

int main()
{
float small = 3.1415926535897932384626;
float large = 6.0234567e17;
float whole = 2.000000000;
cout << "Some values in general format" << endl;
cout << "small: " << small << endl;

declaration for the

ios

class.

cout << "large:


cout << "whole:

" << large << endl;


" << whole << endl << endl;

cout << scientific;


cout
cout
cout
cout

<<
<<
<<
<<

"The values in scientific format" << endl;


"small: " << small << endl;
"large: " << large << endl;
"whole: " << whole << endl << endl;

cout << fixed;


cout
cout
cout
cout

<<
<<
<<
<<

"The same values in


"small: " << small
"large: " << large
"whole: " << whole

fixed format" << endl;


<< endl;
<< endl;
<< endl << endl;

// Doesn't work -- doesn't exist


// cout << general;
cout.unsetf(ios::fixed | ios::scientific);
cout
cout
cout
cout

<<
<<
<<
<<

"Back to
"small:
"large:
"whole:

general format" << endl;


" << small << endl;
" << large << endl;
" << whole << endl << endl;

return 0;
}

produces
Some values in general format
small: 3.14159
large: 6.02346e+17
whole: 2
The values in scientific format
small: 3.141593e+00
large: 6.023457e+17
whole: 2.000000e+00

The same values in fixed format


small: 3.141593
large: 602345661202956288.000000
whole: 2.000000
Back to general format
small: 3.14159
large: 6.02346e+17
whole: 2
setprecision()

An important point about floating point output is the precision, which is roughly the
number of digits displayed for the number. The exact definition of the precision depends
on which output format is currently being used.
In general format, the precision is the maximum number of digits displayed. This includes digits before and after
the decimal point, but does not include the decimal point itself. Digits in a scientific exponent are not included.
In fixed and scientific formats, the precision is the number of digits after the decimal point.
Important Point
The default output precision is 6.

The setprecision manipulator allows you to set the precision used for printing out floating point values. The
manipulator takes an integer argument. The header file <iomanip> must be included to use this manipulator.
showpoint

and

noshowpoint

There is one aspect of printing numbers in general format that is either very nice or very
annoying depending on your point of view. When printing out floating point values, only

as many decimal places as needed (up to the precision) are used to print out the values.
In other words, trailing zeros are not printed. This is nice and compact, but impossible to
get decimal points to line up in tables.
The showpoint manipulator forces trailing zeros to be printed, even though they are not needed. By default this
option is off. As can be seen from previous examples, this manipulator is not needed in fixed or scientific format,
only in general format.
#include <iostream>
using std::cout;
using std::endl;
using std::showpoint;
int main()
{
float lots = 3.1415926535;
float little1 = 2.25;
float little2 = 1.5;
float whole = 4.00000;
cout << "Some values with noshowpoint (the default)" << endl << endl;
cout
cout
cout
cout

<<
<<
<<
<<

"lots:
"little1:
"little2:
"whole:

"
"
"
"

<<
<<
<<
<<

lots << endl;


little1 << endl;
little2 << endl;
whole << endl;

cout << endl << endl;


cout << "The same values with showpoint" << endl << endl;
cout << showpoint;
cout << "lots:
" << lots << endl;
cout << "little1: " << little1 << endl;
cout << "little2: " << little2 << endl;

cout << "whole:


}

" << whole << endl;

return 0;

produces
Some values with noshowpoint (the default)
lots:
little1:
little2:
whole:

3.14159
2.25
1.5
4

The same values with showpoint


lots:
little1:
little2:
whole:

3.14159
2.25000
1.50000
4.00000

You might also like