input/output. objectives in this chapter you will: learn what a stream is and examine input and...
DESCRIPTION
Input/Output Streams I/O: sequence of bytes (stream of bytes) from source to destination Bytes are usually characters, unless program requires other types of information Stream: sequence of characters from source to destination Input Stream: sequence of characters from an input device to the computer Output Stream: sequence of characters from the computer to an output device 3TRANSCRIPT
Input/Output
ObjectivesIn this chapter you will:Learn what a stream is and examine input
and output streamsExplore how to use the input stream
functions get, ignore, fill, putback, and peek
Become familiar with file input and outputBecome familiar with input failure
2
Input/Output StreamsI/O: sequence of bytes (stream of bytes) from
source to destinationBytes are usually characters, unless program
requires other types of information Stream: sequence of characters from source
to destinationInput Stream: sequence of characters from
an input device to the computerOutput Stream: sequence of characters from
the computer to an output device
3
Standard I/O DevicesUse iostream to extract (receive) data from
keyboard and send output to the screeniostream contains definitions of two types
istream - input streamostream - output stream
iostream has two variablescin - stands for common inputcout - stands for common output
4
Using cin and coutTo use cin and cout, the preprocessor
directive #include <iostream> must be used
The declaration is similar to the following C++ statements: istream cin;
ostream cout;
Input stream variables: type istream Output stream variables: type ostream
5
cin and the Extraction Operator >>The syntax of an input statement using cin
and the extraction operator >> iscin >> variable >> variable...;
The extraction operator >> is binaryThe left-hand operand is an input stream
variable such as cinThe right-hand operand is a variable of a
simple data type
6
Standard InputEvery occurrence of >> extracts the next
data item from the input streamTwo variables can be read using a single cin statement
No difference between a single cin with multiple variables and multiple cin statements with one variable
When scanning, >> skips all whitespaceWhitespace characters consist of blanks
and certain nonprintable characters
7
Data Type of Input>> distinguishes between character 2 and
number 2 by the right hand operand of >>If it is of type char, the 2 is treated as
character 2 If it is of the type int (or double) the 2 is
treated as the number 2
8
9
Reading DataWhen reading data into a char variable
Extraction operator >> skips leading whitespace, finds and stores only the next character
Reading stops after a single character
10
Reading Data (Continued)To read data into an int or double variable
Extraction operator >> skips leading whitespace, reads plus or minus sign (if any), reads the digits (including decimal)
Reading stops on whitespace non-digit character
11
Example 3-1 int a, b;double z;char ch, ch1, ch2;
Statement Input Value Stored in Memory
1. cin >> ch; A ch = 'A‘
2. cin >> ch; AB ch = 'A', 'B' is held for later
input
3. cin >> a; 48 a = 48
4. cin >> a; 46.35 a = 46, .35 is held for later input
5. cin >> z; 74.35 z = 74.35
6. cin >> z; 39 z = 39.0
7. cin >> z >> a; 65.78 38 z = 65.78, a = 3812
Statement Input Value Stored in Memory
8. cin >> a >> b; 4 60 a = 4, b = 60
9. cin >> a >> ch >> z; 57 A 26.9 a = 57, ch = 'A', z = 26.9
10.cin >> a >> ch >> z; 57 A26.9 a = 57, ch = 'A', z = 26.9
11.cin >> a >> ch >> z; 57 A26.9 a = 57, ch = 'A', z = 26.9
12.cin >> a >> ch >> z; 57A26.9 a = 57, ch = 'A', z = 26.9
13.cin >> z >> ch >> a; 36.78B34 z = 36.78, ch = 'B', a = 34
14.cin >> z >> ch >> a; 36.78 B34 z = 36.78, ch = 'B', a = 34
15.cin >> a >> b >> z; 11 34 a = 11, b = 34, computer waits for
the next number13
Statement Input Value Stored in Memory
16.cin >> a >> z; 46 32.4 68 a = 46, z = 32.4,
68 is held for later input
17.cin >> a >> z; 78.49 a = 78, z = 0.49
18.cin >> ch >> a; 256 ch = '2', a = 56
19.cin >> a >> ch; 256 a = 256, computer waits for the
input value for ch
20.cin >> ch1 >> ch2; A B ch1 = 'A', ch2 = 'B'
14
cin and the get FunctionThe get function
Inputs next character (including whitespace)Stores character location indicated by its
argumentThe syntax of cin and the get function: cin.get(varChar);varCharIs a char variableIs the argument (parameter) of the function
15
16
The get() function can be used to read a single character.
get() obtains the very next character from the input stream without skipping any leading whitespace characters
Another Way to Read char Data
17
char first; char middle; char last;
cin.get(first); cin.get(middle); cin.get(last);
NOTE: The file reading marker is left pointing to the space after the ‘B’ in the input stream
first middle last
At keyboard you type: A[space]B[space]C[Enter]
first middle last
‘A’ ‘ ’ ‘B’
cin and the ignore Functionignore: discards a portion of the inputThe syntax to use the function ignore is:cin.ignore(intExp, chExp);
intExp is an integer expressionchExp is a char expression
If intExp is a value m, the statement says to ignore the next m characters or all characters until the character specified by chExp
18
19
Use function ignore() to skip charactersThe ignore() function is used to skip(read and discard) characters in the input stream The callcin.ignore(howMany, whatChar);
will skip over up to howMany characters or until whatChar has been read, whichever comes first
20
An Example Using cin.ignore()
a b c
a b c
a b c
a b c
957 34
957 34 128
957 34
NOTE: shows the location of the file reading marker STATEMENTS CONTENTS MARKER
POSITION int a; 957 34 1235\nint b; 128 96\nint c;cin >> a >> b; 957 34 1235\n
128 96\n
cin.ignore(100, ‘\n’); 957 34 1235\n128 96\n
cin >> c; 957 34 1235\n128 96\n
21
Another Example Using cin.ignore()
i ch
957 34
957 34
957 34i ch
i ch
i ch16 ‘A’
‘A’
‘A’
NOTE: shows the location of the file reading marker STATEMENTS CONTENTS MARKER
POSITION int i; A 22 B 16 C 19\n char ch;
cin >> ch; A 22 B 16 C 19\n
cin.ignore(100, ‘B’); A 22 B 16 C 19\n
cin >> i; A 22 B 16 C 19\n
putback and peek Functionsputback function
Places previous character extracted by the get function from an input stream back to that stream
peek functionReturns next character from the input streamDoes not remove the character from that
stream
22
putback and peek Functions (continued)The syntax for putback:
istreamVar.putback(ch);istreamVar - an input stream variable, such as cin
ch is a char variableThe syntax for peek:
ch = istreamVar.peek();istreamVar is an input stream variable (cin)ch is a char variable
23
Dot NotationIn the statement cin.get(ch);
cin and get are two separate identifiers separated by a dot
Dot separates the input stream variable name from the member, or function, name
In C++, dot is the member access operator
24
Disk Files for I/O
your variable
(of type ifstream)
your variable
(of type ofstream)
disk file“myInfile.dat”
disk file“myOut.dat”
executingprogram
input data output data
#include <fstream>
25
Disk I/OTo use disk I/O
Access #include <fstream>Choose valid identifiers for your filestreams
and declare themOpen the files and associate them with disk
namesUse your filestream identifiers in your I/O
statements(using >> and << , manipulators, get, ignore)
Close the files26
Disk I/O Statements#include <fstream>
ifstream myInfile; // Declarations
ofstream myOutfile;
myInfile.open(“myIn.dat”); // Open filesmyOutfile.open(“myOut.dat”);
myInfile.close(); // Close filesmyOutfile.close();
27
Opening a FileOpening a file
Associates the C++ identifier for your file with the physical(disk) name for the fileIf the input file does not exist on disk, open is
not successfulIf the output file does not exist on disk, a new
file with that name is createdIf the output file already exists, it is erased
Places a file reading marker at the very beginning of the file, pointing to the first character in the file
28
Stream Fail StateWhen a stream enters the fail state,
Further I/O operations using that stream have no effect at all
The computer does not automatically halt the program or give any error message
Possible reasons for entering fail state include Invalid input data (often the wrong type) Opening an input file that doesn’t exist Opening an output file on a disk that is
already full or is write-protected
29
Input FailureThings can go wrong during executionIf input data does not match the
corresponding variables, the program may run into problems
Trying to read a letter into an int or double variable would result in an input failure
If an error occurs when reading dataInput stream enters the fail state
30
Input Failure (continued)Once in a fail state, all further I/O statements
using that stream are ignored The program continues to execute with
whatever values are stored in variables This causes incorrect resultsThe clear function restores input stream to a
working stateistreamVar.clear();
31
Run Time File Name Entry#include <string>// Contains conversion function c_str
ifstream inFile;string fileName;
cout << “Enter input file name: “ << endl; // Promptcin >> fileName;
// Convert string fileName to a C string typeinFile.open(fileName.c_str());
32
33
AlgorithmMain Module Level 0
Open files Get social security numberGet nameWrite data in proper formatsClose files
Open Files Level 1inData.open("name.dat")outData.open("name.out")
34
Get Name
Get first nameGet middle name or initialGet last name
Write Data in Proper FormatsWrite first name, blank, middle name, blank, last name, blank, social security numberWrite last name, comma, first name, blank, middle name, blank, social security numberWrite last name, comma, blank, first name, blank, middle initial, period, blank,
social security numberWrite first name, blank, middle initial, period, blank, last name
35
Middle initial Level 2
Set initial to middleName.substr(0, 1) + period
Close filesinData.close()outData.close()
36
C++ Program//*************************************************************// Format Names program// This program reads in a social security number, a first name// a middle name or initial, and a last name from file inData. // The name is written to file outData in three formats: // 1. First name, middle name, last name, and social security // number.// 2. last name, first name, middle name, and social // security number// 3. last name, first name, middle initial, and social// security number// 4. First name, middle initial, last name//*************************************************************
37
#include <fstream> // Access ofstream#include <string> // Access stringusing namespace std;
int main(){ // Declare and open files ifstream inData; ofstream outData; inData.open("name.dat"); outData.open("name.out"); // Declare variables string socialNum; // Social security number string firstName; // First name string lastName; // Last name string middleName; // Middle name string initial; // Middle initial
38
// Read in data from file inData inData >> socialNum >> firstName >> middleName >> lastName; // Access middle initial and append a period initial = middleName.substr(0, 1) + '.'; // Output information in required formats outData << firstName << ' ' << middleName << ' ' << lastName << ' ' << socialNum << endl; outData << lastName << ", " << firstName << ' ' << middleName << ' ' << socialNum << endl; outData << lastName << ", " << firstName << ' ' << initial << ' ' << socialNum << endl; outData << firstName << ' ' << initial << ' ' << lastName; // Close files inData.close(); outData.close(); return 0;
}