3. 3
I/O Streams, DevicesI/O Streams, Devices
Input streamInput stream
• A sequence of characters/bytesA sequence of characters/bytes
• From an input deviceFrom an input device
• Into the computerInto the computer
Output streamOutput stream
• A sequence of characters/bytesA sequence of characters/bytes
• From the computerFrom the computer
• To an output deviceTo an output device
4. 4
Input data is considered to be anInput data is considered to be an
endless sequence of characters/bytesendless sequence of characters/bytes
coming into a program from an inputcoming into a program from an input
device (keyboard, file, etc.)device (keyboard, file, etc.)
Input StreamsInput Streams
... 1 4 19 34 HI MOM. 7 ..
5. 5
cincin and the Extraction Operator >>and the Extraction Operator >>
A binary operatorA binary operator
• Takes two operandsTakes two operands
• Name of an input stream on the leftName of an input stream on the left
•cincin for standard input from keyboardfor standard input from keyboard
• Variable on the rightVariable on the right
Variables can be "cascaded"Variables can be "cascaded"
cin >> amount >> count >> direction;cin >> amount >> count >> direction;
Variables should generally be simpleVariables should generally be simple
typestypes
6. 6
The Extraction Operator >>The Extraction Operator >>
Enables you to do input with the cinEnables you to do input with the cin
commandcommand
Think of the >> as pointing to where theThink of the >> as pointing to where the
data will end updata will end up
C++ able to handle different types of dataC++ able to handle different types of data
and multiple inputs correctlyand multiple inputs correctly
7. 7
The Reading MarkerThe Reading Marker
Keeps track of point in the input streamKeeps track of point in the input stream
where the computer should continuewhere the computer should continue
readingreading
Extraction >> operator leaves readingExtraction >> operator leaves reading
marker following last piece of data readmarker following last piece of data read
… 1 4 19 34 HI MOM. 7 ..
8. 8
The Reading MarkerThe Reading Marker
During execution of a cin commandDuring execution of a cin command
• as long as it keeps finding data, it keeps readingas long as it keeps finding data, it keeps reading
• when the reading marker hits somethingwhen the reading marker hits something notnot data, itdata, it
quitsquits readingreading
Things in the input stream that cin considers notThings in the input stream that cin considers not
datadata
• spacesspaces
• tab ttab t
• newline character nnewline character n
(pressing the RETURN key)(pressing the RETURN key)
• for numeric input, somethingfor numeric input, something nonnonnumericnumeric
9. 9
Input to a Simple VariableInput to a Simple Variable
charchar
• Skips any white space charactersSkips any white space characters
• Reads one characterReads one character
• Any other characters in the stream are heldAny other characters in the stream are held
for later inputfor later input
intint
• Skips white space charactersSkips white space characters
• Reads leading + or -Reads leading + or -
• Reads numeralsReads numerals
• Quits reading when it hits non numeralQuits reading when it hits non numeral
10. 10
Input to a Simple VariableInput to a Simple Variable
double (or float)double (or float)
• Skips leading white spaceSkips leading white space
• Reads leading + or –Reads leading + or –
• Reads numerals and at most one decimalReads numerals and at most one decimal
pointpoint
• Quits reading when it hits something notQuits reading when it hits something not
numericnumeric
Note example, page 95Note example, page 95
11. 11
Predefined FunctionsPredefined Functions
Function in a computer language isFunction in a computer language is similarsimilar
to concept of a function in mathematicsto concept of a function in mathematics
• The function is sent value(s)The function is sent value(s)
• Called "arguments" orCalled "arguments" or
"parameters""parameters"
• It manipulates the valueIt manipulates the value
• It returns a valueIt returns a value
Some functions "do a task"Some functions "do a task"
12. 12
ReadingReading cStringcString Data withData with cincin
Keyboard response ofKeyboard response of twotwo wordswords
(separated by a space) causes the cin(separated by a space) causes the cin
command to quit readingcommand to quit reading
• the space is consideredthe space is considered nonnondata (in spite ofdata (in spite of
our intent)our intent)
???
13. 13
ReadingReading cStringcString DataData
TheThe getline ( )getline ( ) function will allow thefunction will allow the
programmer to access all the charactersprogrammer to access all the characters
charchar Array variable Length (max number
of characters)
Character which
terminates read
14. 14
cincin and theand the getget FunctionFunction
Syntax:Syntax:
cin.get(varChar);cin.get(varChar);
ExampleExample
cin.get (chVal);cin.get (chVal);
•chValchVal is the parameteris the parameter
• the .the .getget function retrieves a character fromfunction retrieves a character from
the keyboardthe keyboard
• stores the character instores the character in chValchVal
15. 15
cincin and theand the ignoreignore FunctionFunction
Syntax:Syntax:
cin.ignore (intValue, charVal);cin.ignore (intValue, charVal);
Example:Example:
cin.ignore (10,'n')cin.ignore (10,'n')
The ignore function causes characters inThe ignore function causes characters in
the input stream to bethe input stream to be ignoreignoredd
(discarded)(discarded)
• In this example for 10 characters … or …In this example for 10 characters … or …
• Until a newline character occursUntil a newline character occurs
• It also discards the newline characterIt also discards the newline character
The ignore and get also
work for other input
streams (such as file input
streams)
The ignore and get also
work for other input
streams (such as file input
streams)
16. 16
Using theUsing the getline( )getline( )
Problem : the getline( ) quits reading when it finds aProblem : the getline( ) quits reading when it finds a
newlinenewline
• Suppose you have terminatedSuppose you have terminated previous inputprevious input with thewith the
<RETURN> key (newline still in input stream)<RETURN> key (newline still in input stream)
• getline ( ) finds the newlinegetline ( ) finds the newline immediatelyimmediately and declares itsand declares its
task finishedtask finished
• we must somehow discard the newline in the input streamwe must somehow discard the newline in the input stream
???
17. 17
Using the ignore( )Using the ignore( )
Solution : the ignore( ) commandSolution : the ignore( ) command
Tells the program to skip either the next 10Tells the program to skip either the next 10
characters or until it reaches a newlinecharacters or until it reaches a newline
• whichever comes firstwhichever comes first
This effectively discards the newlineThis effectively discards the newline
18. 18
Input FailureInput Failure
Happens when value in the input stream isHappens when value in the input stream is
invalid for the variableinvalid for the variable
int x, y;int x, y;
cin >> x >> y; // Enter B 37cin >> x >> y; // Enter B 37
Value of 'B' not valid for an intValue of 'B' not valid for an int
ViewView exampleexample When an input stream failsWhen an input stream fails
system ignores all further I/Osystem ignores all further I/O
19. 19
TheThe clearclear FunctionFunction
Use the clear to return the input stream toUse the clear to return the input stream to
a working statea working state
ExampleExample
look forlook for
cin.clear()cin.clear()
cin.ignore (200,'n');cin.ignore (200,'n');
// to empty out input stream// to empty out input stream
20. 20
Formatting OutputFormatting Output
Producing proper output in the properProducing proper output in the proper
format is importantformat is important
• Specify decimal precisionSpecify decimal precision
• Specify left or right justificationSpecify left or right justification
• Align columns of numbersAlign columns of numbers
C++ provides I/O manipulatorsC++ provides I/O manipulators
Syntax:Syntax:
cout <<cout << manipulatormanipulator << expression …<< expression …
21. 21
ManipulatorsManipulators
Must first of allMust first of all
#include <iomanip>#include <iomanip>
For decimal precision useFor decimal precision use
cout << setprecision (n) << …cout << setprecision (n) << …
To output floating point numbers in fixedTo output floating point numbers in fixed
decimal format usedecimal format use
cout << fixed << …cout << fixed << …
To force decimal zeros to showTo force decimal zeros to show
cout << showpoint << …cout << showpoint << …
22. 22
ManipulatorsManipulators
To specify right justification in a specifiedTo specify right justification in a specified
number of blanks usenumber of blanks use
cout << setw(n) << …cout << setw(n) << …
If the number of blanks required to printIf the number of blanks required to print
the expression exceeds specified sizethe expression exceeds specified size
• Size is ignoredSize is ignored
Problem – print series of names leftProblem – print series of names left
justified followed by right justified numbersjustified followed by right justified numbers
Osgood Smart 1.23Osgood Smart 1.23
Joe Schmo 456.78Joe Schmo 456.78
•Names are of different length
•Need variable number of spaces
23. 23
ManipulatorsManipulators
Print name, then variable number of spacesPrint name, then variable number of spaces
using the setw( )using the setw( )
ExampleExample
cout << showpoint << fixed ;cout << showpoint << fixed ;
cout << name <<cout << name <<
setw( 25 - strlen(name))<<" ";setw( 25 - strlen(name))<<" ";
cout << setw (8) <<cout << setw (8) <<
setprecision(2) << amt;setprecision(2) << amt;
24. 24
Formatting ToolsFormatting Tools
Possible to specify a character to fillPossible to specify a character to fill
leading spacesleading spaces
cout.fill ('*');cout.fill ('*');
cout << setw(10) <<cout << setw(10) <<
setprecision(2);setprecision(2);
cout << pmtAmountcout << pmtAmount ;;
ResultResult
*****12.34*****12.34
25. 25
File I/OFile I/O
Previous discussion has considered inputPrevious discussion has considered input
from the keyboardfrom the keyboard
• This works fine for limited inputThis works fine for limited input
• Larger amounts of data will require file inputLarger amounts of data will require file input
File:File:
An area of secondary storage used to holdAn area of secondary storage used to hold
informationinformation
Keyboard I/OKeyboard I/O #include <iostream>#include <iostream>
File I/OFile I/O #include <fstream>#include <fstream>
26. 26
File I/OFile I/O
Requirements to do file I/ORequirements to do file I/O
1.1. #include <fstream>#include <fstream>
2.2. Declare a file stream variableDeclare a file stream variable
ifstream or ofstreamifstream or ofstream
3.3. Open the file – use the commandOpen the file – use the command
whateverFile.open("filename.xxx");whateverFile.open("filename.xxx");
4.4. Use the stream variable withUse the stream variable with >>>> oror <<<<
5.5. Close the fileClose the file whateverFile.close();whateverFile.close();
27. 27
File Open ModesFile Open Modes
In some situations you must specify one orIn some situations you must specify one or
more modes for the filemore modes for the file
Syntax:Syntax:
fileVariable.open("filename.xxx", fileOpenMode);fileVariable.open("filename.xxx", fileOpenMode);
28. 28
Using Files in ProgramsUsing Files in Programs
SpecifySpecify #include#include
<fstream><fstream>
header fileheader file
Declare instance ofDeclare instance of
file to be usedfile to be used
Prepare for accessPrepare for access
withwith .open( ).open( )
commandcommand
Use name of file inUse name of file in
place of cin or coutplace of cin or cout
file name on diskfile name on disk
#include <fstream>