INPUT AND OUPUT
STREAMS
By Sir. Joshua
Introduction
Inputand output streams enable a user to
interact with the program by displaying
output on the screen and getting the user’s
input through the keyboard.
…
The <iostream> library provides objects which
can read user input and output data to the console
or to a file.
In C++,
Input stream uses cin object together with
extraction operator (>>) to read data from the
source/keyboard to the program.
Output stream uses cout together with insertion
operator (<<) to display output to the screen.
Displaying data to destination/screen
(output stream)
Thecout object, together with the <<
(insertion) operator, is used to output
values/print text:
Example
New Lines (in C++ Outputs)
This
is applied when we want to display texts
in multiple lines
To
insert a new line, you can use the \n
character:
Example:
…
Another
way to insert a new line, is with the
endl manipulator:
Example:
Escape sequences
Escapesequence is a character precededed
by a backslash (\) and has a special
meaning.
Some of these escape sequence include:
Horizontal tab (\t)
Vertical tab (\v)
New line (\n)
Quotation mark (\’) or (\”)
Reading data from the source
Thecin object, together with the >>
(extraction) operator, is used to read/get
values from user:
Example:
…
Youcan also use more than one extraction
operators to request more than one data
from the user
For example
Activity
Writea C++ program that will prompt user
to enter and finally display the following:
• User’s age (eg: 18, 17, etc)
• User’s FirstName (eg: John, Emmanuel, etc)
Note:
• Each information must be displayed in a new
line.
Getting Texts with more than one
word
Theuse of cin together with >> operator is
not enough when we want to get a text with
many words from user.
The
getline command can be used to
handle this challenge, as shown in this
example:
C++ iostream objects
Object Description
cerr An output stream for error messages
clog An output stream to log program information
cin An input stream that reads keyboard input from the console by default
cout An output stream which writes output to the console by default
wcerr The same as cerr but outputs wide char (wchar_t) data rather
than char data
wclog The same as clog but outputs wide char (wchar_t) data rather
than char data
wcin The same as cin but interprets each input character as a wide char
(wchar_t)
wcout The same as cout but outputs wide char (wchar_t) data rather
than char data
Exercise
Usingoutput stream “cout” , write a C++
program that displays the following table as
shown in Figure
Design an algorithm and then write a C++
program that reads two numbers entered by the
user from the keyboard, calculates their sum, and
displays the result on the screen.
…