Lecture 1: Overview - City University of New York
Download
Report
Transcript Lecture 1: Overview - City University of New York
Lecture 6: Input/Output (II)
Introduction to Computer Science
Spring 2006
1
Contents
Write data to the standard output device
Use manipulators in a program to format
output
Perform input and output operations with the
string data type
File input and output
2
Writing to Standard Output
Syntax of cout when used with <<
cout<<expression or manipulator
<<expression or manipulator...;
Expression is evaluated
Value is printed
Manipulator is used to format the output
3
Formatting Output
endl manipulator moves output to the
beginning of the next line
setprecision(n) outputs decimal numbers with
up to n decimal places
fixed outputs floating-point numbers in a
fixed decimal format
showpoint forces output to show the decimal
point and trailing zeros
4
The setw Manipulator
setw outputs the value of an expression in
specific columns
If the number of columns exceeds the
number of columns required by the
expression
Output of the expression is right-justified
Unused columns to the left are filled with spaces
5
The flush Function
flush clears the buffer, even if it is not full
Unlike endl, it does not move the cursor to
the beginning of the next line
The syntax for flush:
ostreamVar.flush();
ostreamVar is an output stream variable
flush can be used as a manipulator
cout<<flush;
6
Additional Output Formatting Tools
Output stream variables can use setfill to fill
unused columns with a character
left: left-justifies the output
ostreamVar<<left;
Disable left by using unsetf
right: right-justifies the output
ostreamVar << right;
7
Types of Manipulators
Two types of manipulators:
With parameters
Without parameters
Parameterized: require iomanip header
setprecision, setw, and setfill
Nonparameterized: require iostream header
endl, fixed, showpoint, left, and flush
8
I/O and the string Type
An input stream variable (cin) and extraction
operator >> can read a string into a variable
of the data type string
Extraction operator
Skips any leading whitespace characters and
reading stops at a whitespace character
Should not be used to read strings with blanks
The function getline
Reads until end of the current line
Should be used to read strings with blanks
9
File Input/Output
File: area in secondary storage to hold info
File I/O
1.
2.
3.
4.
5.
Include fstream header
Declare file stream variables
Associate the file stream variables with the
input/output sources
Use the file stream variables with >>, <<, or
other input/output functions
Close the filesFile Input/Output
10
End of lecture 6
Thank you!
11