Chapter 5 - Input and Output Streams

Download Report

Transcript Chapter 5 - Input and Output Streams

Chapter 5
Input and Output
Streams
5.1 Input and Output Streams
I/O (Input and Output) incorporates
streams or flows of information
•
Flow runs from input device (keyboard) into
program
•
Flow runs from program to an output device
(console window or screen)
•
Need to include <iostream>
#Page
2
5.1.1 Namespaces and I/O Streams
Three Options for accessing individual components of
the header file – Method 3 preferred
// Method 1 -- PREFERRED METHOD
#include <iostream>
using namespace std;
...
cout << "Hello World";
// Method 2
#include <iostream>
...
std::cout << "Hello World";
// Method 3
#include <iostream>
using std::cout;
...
cout << "Hello World";
#Page
3
5.1.2 The cout Statement
Displays information to the screen
• cout represents console output
• Information displayed includes literals,
constants and variables
• cout << "Hello World";
// Writes the literal “Hello World” to the screen
• Insertion operator ( << )
Inserts the information into the cout stream
#Page
4
5.1.2 The cout Statement
Example with multiple lines:
char grade = 'B';
float class_avg = 88.5;
// Notice there isn’t a semicolon at the
// end of the first line
cout << "Your average is: " << class_avg
<< "\nYour grade is: " << grade;
// Output
Your average is: 88.5
Your grade is: B
#Page
5
5.1.3 The cin Statement
Reads data from input stream and stores that
value, if possible, into the variable used in the
cin statement
cin - console input
Example: reading from keyboard
int score = 0;
cin >> score;
Extraction operator (>>)
Extracts information from the stream
#Page
6
5.1.3 The cin Statement
Right operand of the extraction operator must
be a variable or variables
Method 1: Reading multiple values
int score1 = 0, score2 = 0;
cout << "Enter two scores: ";
cin >> score1
>> score2;
#Page
7
5.1.3 The cin Statement
Another Method: Reading multiple values
(better approach)
int score1 = 0, score2 = 0;
cout << "Enter first score: ";
cin >> score1;
cout << "Enter second score: ";
cin >> score2;
#Page
8
5.2 The endl Manipulator
Moves cursor to the next line
endl stands for end line
Manipulator - command directly placed into
the stream
• Information inserted into the stream is sent to the output
buffer (area in memory)
• Information stays in the buffer until signaled to write
entire buffer to the screen (i.e., flushing the buffer)
#Page
9
5.2.1 The endl Manipulator Versus '\n'
Both endl and '\n' move the cursor to the next line;
only endl flushes the buffer
Preferred method:
• Use '\n' when possible unless you need to flush the
output buffer
• No more than one endl per cout
• Use endl only at the end of a cout
float money = 123.45F;
cout << "You have $" << money << endl;
cout << "Your turn to buy!" << endl;
// Output
You have $123.45
Your turn to buy!
#Page
10
5.3 Input and Output Buffers
Buffer - area of memory that holds data
Input buffer - holds data to be read via a cin
Output buffer - holds data generated by a cout
statement
• Speeds up writing to the screen
• Faster to write a lot of information once to the output
device rather than having multiple writes with one
piece of data
#Page
11
5.4 Formatting the Output Stream
Number of options available for formatting
output
Two unique ways for formatting cout:
1. Member functions –accessed via cout
Syntax for using cout member functions:
cout.<function_name> ( <parameters> );
Parameters - data we supply to the function
#Page
12
5.4 Formatting the Output Stream
2. Manipulators - commands placed directly
into the output stream
Manipulators and member functions basically
accomplish same job
#Page
13
5.4 Formatting Member Functions & Manipulators
Member Function
Manipulator
Description
<iostream>
<iomanip>
Required header files
.width
setw
Set the total width for the displayed
data
.precision
setprecision
Places to the right of the decimal point
.setf( ios::right )
Right
Right justify
.setf( ios::left )
left
Left justify
.setf( ios::fixed )
fixed
Decimal notation
.setf( ios::scientific )
scientific
Scientific notation
.setf( ios::showpos )
showpos
Show sign of all numbers even if
positive
.setf( ios::showpoint )
showpoint
Show trailing zeros
.flush
flush
Flushes the output buffer
#Page
14
5.4.1 The .width Member Function and setw Manipulator
width member function and setw
manipulator - specify amount of space a
piece of data will occupy on the screen
Default - data printed to screen with no
additional padding
• Padding - spaces on either side of the data
• If data doesn’t fill allotted space, the data is
padded with spaces
#Page
15
5.4.1 The .width Member Function and setw Manipulator
Which side of data spaces appear on
depends upon justification
• If right justified, spaces are on left side of the
data
• If left justified, spaces appear on right
• Default, right justified
If the data is larger than the specified width, it will not
be truncated; just does not appear with padding
#Page
16
5.4.1 The .width Member Function and setw Manipulator
Strings - usually left justified
Numbers - right justified / decimals aligned
Sample Justification:
Willy
Marcus
Calvin
Makit
Sunkenship
Cowboy
#Page
1.92
3.75
.56
17
5.4.1 The .width Member Function and setw Manipulator
The .width Member Function
float money = 123.45F;
cout << "You have $";
cout.width( 20 );
cout << money << endl;
// Output
You have $
123.45
#Page
18
5.4.1 The setw Manipulator
#include <iostream> // Needed for cout
#include <iomanip> // Needed for setw
using namespace std;
int main()
{
float money = 123.45F;
cout << "You have $";
cout << setw( 20 ) << money << endl;
return 0;
}
// Output
You have $
123.45
#Page
There are 14
spaces between
the literal and
the value in
money
Always count
the decimal
point as a
character when
calculating total
space required
for output
19
5.4.2 The .precision Member & setprecision Manipulator
.precision member function and
setprecision manipulator - sets number
of digits displayed to the right of the decimal
place
• Unlike .width and setw, these are not volatile
- precision remains set until a different value is
given
#Page
20
5.4.3 The .setf member function
.setf member function – performs a
variety of formatting tasks by incorporating
flags
• Flag – value that represents a specific setting
or state
setf - stands for set flag
#Page
21
5.4.3 The .setf member function
.setf member function – performs a
variety of formatting tasks by incorporating
flags (continued)
• A flag representing the desired formatting
function is passed to .setf
• For every flag passed to .setf, there is a
corresponding manipulator with the same
name as the flag
#Page
22
5.4.3 The .setf Member Function Example
#include <iostream>
#include <iomanip> // Needed for manipulators
using namespace std;
int main()
{
float money = 123.45F;
cout << "You have $";
cout.setf( ios::fixed ); // Decimal notation
cout << setprecision( 2 ) << money << endl;
return 0;
}
// Output
You have $123.45
#Page
23
5.4.3 Corresponding Manipulators
For every flag passed to .setf, there is a
corresponding manipulator with the same
name as the flag
using namespace std;
...
cout << fixed << setprecision( 2 ) << money << endl;
Any flag set can be unset using member
function unsetf
#Page
24
5.4.4 The .flush Member and the Flush Manipulator
.flush member function and the
manipulator - both flush the output buffer
without creating a new line
// Member function
cout.flush();
// Manipulator
cout << flush;
#Page
25
5.5 Debugging
Debugger - set of tools to analyze a
program line by line while running
• Debugger can only help find logic and runtime
errors
• Syntax errors must be resolved before an
executable is built
#Page
26
5.5.1 Step Into, Step Over, & Step Out
Step Into tool - executes the current line
Line being
executed
designated by a
yellow arrow in the
left margin
If current line is a function call or routine, Step Into
attempts to step into the code within that function or
routine
Usually undesirable if the function
or routine is predefined
#Page
27
5.5.1 Step Into, Step Over, & Step Out
Step Over - executes current line without
stepping into the code within that function or
routine
Toolbar icons & hot keys
Tool
Step Out - returns to
where undesirable
code was entered
#Page
Icon
Hot Key
Step
Into
F11
Step
Over
F10
Step Out
Shift+F11
28
5.5.2 Run to Cursor
Step tools - often time consuming to use to
step over each line until an error is
encountered in larger programs
Run to Cursor – known working code can be
bypassed by placing cursor on any executable
line and selecting Run to Cursor
• Program runs normally until that line of code has been
reached - execution then stops - can continue by using
the “step” tools to resume line by line execution
#Page
29
5.5.2 Run to Cursor
Executed by right clicking in code window
and choosing Run to Cursor from displayed
popup menu
Ctrl + F10 hot key - starts Run to Cursor process
#Page
30
5.5.3 Breakpoints
Breakpoints - accomplish same basic
functionality as Run to Cursor
• Can have multiple breakpoints located
strategically throughout the code
• Start Debugging option runs to the first
breakpoint
#Page
31
5.5.3 Breakpoints
Once program started using any of the debugging
tools, Resume option jumps to next breakpoint
To place a breakpoint on a
line of code - click in the
left margin on the desired
line
Red circle marks the
breakpoints
#Page
32
5.5.3 Breakpoints
Additional options for working with
breakpoints
• Toggle Breakpoints (F9) – sets or removes a
breakpoint on current line as designated by the
cursor
• Delete All Breakpoints (Shift + Ctrl + F9) –
permanently removes all breakpoints
• Disable/Enable All Breakpoints – temporarily
turns all breakpoints on or off
#Page
33
5.5.4 Watches
Watches – used to examine contents, or the
state, of variables, constants, and expressions
Windows provided: Autos, Locals, and Watch1 4
• Autos window - shows variables within a few lines of
the current line of execution
• Locals window - shows variables within current
scope
• Scope - area in which a variable can be seen
(more later)
• Watch (1 - 4) - for programmer to examine variables
of their choice
#Page
34
5.5.4 Watches
Hovering over a variable while debugging
also displays a popup window containing
variable’s name and value
Autos watch window
#Page
35
Character Input
Reading in a character
char ch;
cin >> ch;
// Reads in any non-blank char
cin.get(ch); // Reads in any char
cin.ignore(); // Skips over next char in
// the input buffer
3-36
Stream Manipulators
Used to control features of an output field
Some affect just the next value displayed
• setw(x): Print in a field at least x spaces
wide. Use more spaces if specified field width
is not big enough.
3-37
Stream Manipulators
Some affect values until changed again
• fixed: Use decimal notation (not E-notation) for
floating-point values.
• setprecision(x):
• When used with fixed, print floating-point value using x
digits after the decimal.
• Without fixed, print floating-point value using x significant
digits.
• showpoint: Always print decimal point for floatingpoint values.
• left, right: left-, right justification of value
3-38
Manipulator Examples
const float e = 2.718;
float price = 18.0;
cout << setw(8) << e << endl;
cout << left << setw(8) << e
<< endl;
cout << setprecision(2);
cout << e << endl;
cout << fixed << e << endl;
cout << setw(6) << price;
3-39
Displays
^^^2.718
2.718^^^
2.7
2.72
^18.00
3.9 Working with Characters and
String Objects
char: holds a single character
string: holds a sequence of characters
Both can be used in assignment statements
Both can be displayed with cout and <<
3-40
String Input
Reading in a string object
string str;
cin >> str;
// Reads in a string
// with no blanks
getline(cin, str); // Reads in a string
// that may contain
// blanks
3-41
Character Input
Reading in a character
char ch;
cin >> ch;
// Reads in any non-blank char
cin.get(ch); // Reads in any char
cin.ignore(); // Skips over next char in
// the input buffer
3-42
String Operators
= Assigns a value to a string
string words;
words = "Tasty ";
+ Joins two strings together
string s1 = "hot", s2 = "dog";
string food = s1 + s2; // food = "hotdog"
+= Concatenates a string onto the end of another one
words += food; // words now = "Tasty hotdog"
3-43