chapter 3 malik
TRANSCRIPT
Input and OutputInput and OutputInput and OutputInput and Output
Chapter 3Chapter 3Chapter 3Chapter 3
2
Chapter TopicsChapter TopicsChapter TopicsChapter Topics I/O Streams, DevicesI/O Streams, Devices Predefined FunctionsPredefined Functions Input FailureInput Failure Formatting OutputFormatting Output Formatting ToolsFormatting Tools File I/OFile I/O
I/O Streams, DevicesI/O Streams, Devices Predefined FunctionsPredefined Functions Input FailureInput Failure Formatting OutputFormatting Output Formatting ToolsFormatting Tools File I/OFile I/O
3
I/O Streams, DevicesI/O Streams, DevicesI/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
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
Input data is considered to be an Input data is considered to be an endless sequence of characters/bytes endless sequence of characters/bytes coming into a program from an input coming into a program from an input device (keyboard, file, etc.)device (keyboard, file, etc.)
Input data is considered to be an Input data is considered to be an endless sequence of characters/bytes endless sequence of characters/bytes coming into a program from an input coming into a program from an input device (keyboard, file, etc.)device (keyboard, file, etc.)
Input StreamsInput StreamsInput StreamsInput Streams
... 1 4 19 34 HI MOM. 7 ..
5
cincin and the Extraction Operator >> and the Extraction Operator >>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 keyboard for 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 simple typesVariables should generally be simple types
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 keyboard for 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 simple typesVariables should generally be simple types
6
The Extraction Operator >>The Extraction Operator >>The Extraction Operator >>The Extraction Operator >> Enables you to do input with the cin Enables you to do input with the cin
commandcommand Think of the >> as pointing to where the Think of the >> as pointing to where the
data will end updata will end up C++ able to handle different types of data C++ able to handle different types of data
and multiple inputs correctlyand multiple inputs correctly
Enables you to do input with the cin Enables you to do input with the cin commandcommand
Think of the >> as pointing to where the Think of the >> as pointing to where the data will end updata will end up
C++ able to handle different types of data C++ able to handle different types of data and multiple inputs correctlyand multiple inputs correctly
7
The Reading MarkerThe Reading MarkerThe Reading MarkerThe Reading Marker Keeps track of point in the input stream Keeps track of point in the input stream
where the computer should continue where the computer should continue readingreading
Extraction >> operator leaves reading Extraction >> operator leaves reading marker following last piece of data readmarker following last piece of data read
Keeps track of point in the input stream Keeps track of point in the input stream where the computer should continue where the computer should continue readingreading
Extraction >> operator leaves reading Extraction >> operator leaves reading marker following last piece of data readmarker following last piece of data read
… 1 4 19 34 HI MOM. 7 ..
8
The Reading MarkerThe Reading MarkerThe 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 something when the reading marker hits something notnot data, it data, it quitsquits reading reading
Things in the input stream that cin considers not Things in the input stream that cin considers not datadata• spacesspaces• tab \ttab \t• newline character \n newline character \n
(pressing the RETURN key)(pressing the RETURN key)
• for numeric input, something for numeric input, something nonnonnumericnumeric
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 something when the reading marker hits something notnot data, it data, it quitsquits reading reading
Things in the input stream that cin considers not Things in the input stream that cin considers not datadata• spacesspaces• tab \ttab \t• newline character \n newline character \n
(pressing the RETURN key)(pressing the RETURN key)
• for numeric input, something for numeric input, something nonnonnumericnumeric
9
Input to a Simple VariableInput to a Simple VariableInput 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 held Any 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
charchar• Skips any white space charactersSkips any white space characters• Reads one characterReads one character• Any other characters in the stream are held Any 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
Input to a Simple VariableInput to a Simple VariableInput 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 decimal Reads numerals and at most one decimal
pointpoint• Quits reading when it hits something not Quits reading when it hits something not
numericnumeric
Note example, page 95Note example, page 95
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 decimal Reads numerals and at most one decimal
pointpoint• Quits reading when it hits something not Quits reading when it hits something not
numericnumeric
Note example, page 95Note example, page 95
11
Predefined FunctionsPredefined FunctionsPredefined FunctionsPredefined Functions Function in a computer language is Function 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" or Called "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"
Function in a computer language is Function 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" or Called "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
Reading Reading cStringcString Data with Data with cincinReading Reading cStringcString Data with Data with cincin Keyboard response of Keyboard response of twotwo words words
(separated by a space) causes the cin (separated by a space) causes the cin command to quit readingcommand to quit reading• the space is considered the space is considered nonnondata (in spite of data (in spite of
our intent)our intent)
Keyboard response of Keyboard response of twotwo words words (separated by a space) causes the cin (separated by a space) causes the cin command to quit readingcommand to quit reading• the space is considered the space is considered nonnondata (in spite of data (in spite of
our intent)our intent)
???
13
Reading Reading cStringcString Data DataReading Reading cStringcString Data Data The The getline ( ) getline ( ) function will allow the function will allow the
programmer to access all the charactersprogrammer to access all the characters The The getline ( ) getline ( ) function will allow the function 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
cincin and the and the getget Function Functioncincin and the and the getget Function Function Syntax:Syntax:cin.get(varChar);cin.get(varChar);
ExampleExamplecin.get (chVal);cin.get (chVal);•chValchVal is the parameter is the parameter
• the .the .getget function retrieves a character from function retrieves a character from the keyboardthe keyboard
• stores the character in stores the character in chValchVal
Syntax:Syntax:cin.get(varChar);cin.get(varChar);
ExampleExamplecin.get (chVal);cin.get (chVal);•chValchVal is the parameter is the parameter
• the .the .getget function retrieves a character from function retrieves a character from the keyboardthe keyboard
• stores the character in stores the character in chValchVal
15
cincin and the and the ignoreignore Function Functioncincin and the and the ignoreignore Function Function 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 in The ignore function causes characters in the input stream to be the input stream to be ignoreignored d (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
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 in The ignore function causes characters in the input stream to be the input stream to be ignoreignored d (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
Using the Using the getline( )getline( )Using the Using the getline( )getline( ) Problem : the getline( ) quits reading when it finds a Problem : the getline( ) quits reading when it finds a
newlinenewline• Suppose you have terminated Suppose you have terminated previous inputprevious input with the with the
<RETURN> key (newline still in input stream)<RETURN> key (newline still in input stream)• getline ( ) finds the newline getline ( ) finds the newline immediatelyimmediately and declares its and declares its
task finishedtask finished• we must somehow discard the newline in the input streamwe must somehow discard the newline in the input stream
Problem : the getline( ) quits reading when it finds a Problem : the getline( ) quits reading when it finds a newlinenewline• Suppose you have terminated Suppose you have terminated previous inputprevious input with the with the
<RETURN> key (newline still in input stream)<RETURN> key (newline still in input stream)• getline ( ) finds the newline getline ( ) finds the newline immediatelyimmediately and declares its and 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
Using the ignore( )Using the ignore( )Using the ignore( )Using the ignore( ) Solution : the ignore( ) commandSolution : the ignore( ) command Tells the program to skip either the next 10 Tells 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
Solution : the ignore( ) commandSolution : the ignore( ) command Tells the program to skip either the next 10 Tells 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
Input FailureInput FailureInput FailureInput Failure Happens when value in the input stream is Happens when value in the input stream is
invalid for the variableinvalid for the variableint 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
View View exampleexample
Happens when value in the input stream is Happens when value in the input stream is invalid for the variableinvalid for the variableint 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
View View exampleexample When an input stream fails When an input stream fails system ignores all further I/Osystem ignores all further I/O
19
The The clearclear Function FunctionThe The clearclear Function Function Use the clear to return the input stream to Use the clear to return the input stream to
a working statea working state ExampleExample
look for look for cin.clear()cin.clear()cin.ignore (200,'\n'); cin.ignore (200,'\n'); // to empty out input stream// to empty out input stream
Use the clear to return the input stream to Use the clear to return the input stream to a working statea working state
ExampleExamplelook for look for cin.clear()cin.clear()cin.ignore (200,'\n'); cin.ignore (200,'\n'); // to empty out input stream// to empty out input stream
20
Formatting OutputFormatting OutputFormatting OutputFormatting Output Producing proper output in the proper Producing 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 …
Producing proper output in the proper Producing 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
ManipulatorsManipulatorsManipulatorsManipulators Must first of all Must first of all #include <iomanip>#include <iomanip>
For decimal precision useFor decimal precision usecout << setprecision (n) << …cout << setprecision (n) << …
To output floating point numbers in fixed To output floating point numbers in fixed decimal format usedecimal format usecout << fixed << …cout << fixed << …
To force decimal zeros to showTo force decimal zeros to showcout << showpoint << …cout << showpoint << …
Must first of all Must first of all #include <iomanip>#include <iomanip>
For decimal precision useFor decimal precision usecout << setprecision (n) << …cout << setprecision (n) << …
To output floating point numbers in fixed To output floating point numbers in fixed decimal format usedecimal format usecout << fixed << …cout << fixed << …
To force decimal zeros to showTo force decimal zeros to showcout << showpoint << …cout << showpoint << …
22
ManipulatorsManipulatorsManipulatorsManipulators To specify right justification in a specified To specify right justification in a specified
number of blanks usenumber of blanks usecout << setw(n) << …cout << setw(n) << …
If the number of blanks required to print If 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 left Problem – print series of names left justified followed by right justified numbersjustified followed by right justified numbersOsgood Smart 1.23Osgood Smart 1.23Joe Schmo 456.78Joe Schmo 456.78
To specify right justification in a specified To specify right justification in a specified number of blanks usenumber of blanks usecout << setw(n) << …cout << setw(n) << …
If the number of blanks required to print If 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 left Problem – print series of names left justified followed by right justified numbersjustified followed by right justified numbersOsgood Smart 1.23Osgood Smart 1.23Joe Schmo 456.78Joe Schmo 456.78
•Names are of different length
•Need variable number of spaces
23
ManipulatorsManipulatorsManipulatorsManipulators Print name, then variable number of spaces Print name, then variable number of spaces
using the setw( )using the setw( ) Example Example 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;
Print name, then variable number of spaces Print name, then variable number of spaces using the setw( )using the setw( )
Example Example 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
Formatting ToolsFormatting ToolsFormatting ToolsFormatting Tools Possible to specify a character to fill Possible to specify a character to fill
leading spacesleading spacescout.fill ('*');cout.fill ('*');cout << setw(10) << cout << setw(10) << setprecision(2); setprecision(2);cout << pmtAmount cout << pmtAmount ;;
ResultResult*****12.34*****12.34
Possible to specify a character to fill Possible to specify a character to fill leading spacesleading spacescout.fill ('*');cout.fill ('*');cout << setw(10) << cout << setw(10) << setprecision(2); setprecision(2);cout << pmtAmount cout << pmtAmount ;;
ResultResult*****12.34*****12.34
25
File I/OFile I/OFile I/OFile I/O Previous discussion has considered input Previous 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 hold An area of secondary storage used to hold informationinformation
Keyboard I/O Keyboard I/O #include <iostream>#include <iostream> File I/O File I/O #include <fstream>#include <fstream>
Previous discussion has considered input Previous 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 hold An area of secondary storage used to hold informationinformation
Keyboard I/O Keyboard I/O #include <iostream>#include <iostream> File I/O File I/O #include <fstream>#include <fstream>
26
File I/OFile I/OFile 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 variableifstream or ofstream ifstream or ofstream
3.3. Open the file – use the command Open the file – use the command whateverFile.open("filename.xxx");whateverFile.open("filename.xxx");
4.4. Use the stream variable with Use the stream variable with >>>> or or <<<<
5.5. Close the file Close the file whateverFile.close();whateverFile.close();
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 variableifstream or ofstream ifstream or ofstream
3.3. Open the file – use the command Open the file – use the command whateverFile.open("filename.xxx");whateverFile.open("filename.xxx");
4.4. Use the stream variable with Use the stream variable with >>>> or or <<<<
5.5. Close the file Close the file whateverFile.close();whateverFile.close();
27
File Open ModesFile Open ModesFile Open ModesFile Open Modes In some situations you must specify one or In 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);
In some situations you must specify one or In 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
Using Files in ProgramsUsing Files in ProgramsUsing Files in ProgramsUsing Files in Programs Specify Specify #include#include <fstream><fstream> header fileheader file
Declare instance of Declare instance of file to be usedfile to be used
Prepare for access Prepare for access
with with .open( ).open( ) commandcommand
Use name of file in Use name of file in place of cin or coutplace of cin or cout
Specify Specify #include#include <fstream><fstream> header fileheader file
Declare instance of Declare instance of file to be usedfile to be used
Prepare for access Prepare for access
with with .open( ).open( ) commandcommand
Use name of file in Use name of file in place of cin or coutplace of cin or cout
file name on diskfile name on disk
#include <fstream>