SlideShare a Scribd company logo
1 of 28
Input and OutputInput and Output
Chapter 3Chapter 3
2
Chapter 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
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
 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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>

More Related Content

What's hot

What's hot (16)

03. Operators Expressions and statements
03. Operators Expressions and statements03. Operators Expressions and statements
03. Operators Expressions and statements
 
CPU INPUT OUTPUT
CPU INPUT OUTPUT CPU INPUT OUTPUT
CPU INPUT OUTPUT
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Input and output in c
Input and output in cInput and output in c
Input and output in c
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
C programming_MSBTE_Diploma_Pranoti Doke
C programming_MSBTE_Diploma_Pranoti DokeC programming_MSBTE_Diploma_Pranoti Doke
C programming_MSBTE_Diploma_Pranoti Doke
 
C++
C++C++
C++
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 

Viewers also liked

Prakriya ap presentation
Prakriya ap presentationPrakriya ap presentation
Prakriya ap presentationakshayayoume
 
The Man Behind the Majestic Heli Vincent inc.
The Man Behind the Majestic Heli Vincent inc.The Man Behind the Majestic Heli Vincent inc.
The Man Behind the Majestic Heli Vincent inc.Denis Vincent
 
Business Mentor Perth Balanced Scorecard Presentation 1.7
Business Mentor Perth   Balanced Scorecard Presentation 1.7Business Mentor Perth   Balanced Scorecard Presentation 1.7
Business Mentor Perth Balanced Scorecard Presentation 1.7Mentors Business & Executive
 
Business Mentor Perth Balanced Scorecard Presentation 1.6
Business Mentor Perth   Balanced Scorecard Presentation 1.6Business Mentor Perth   Balanced Scorecard Presentation 1.6
Business Mentor Perth Balanced Scorecard Presentation 1.6Mentors Business & Executive
 
486 s12-03-io-devices
486 s12-03-io-devices486 s12-03-io-devices
486 s12-03-io-devicesOshal Shah
 
De brandende rivier en een biertje Blauwalg
De brandende rivier en een biertje BlauwalgDe brandende rivier en een biertje Blauwalg
De brandende rivier en een biertje BlauwalgMenno Bakker
 
http___www.aphref.aph.gov.au_house_committee_ee_bullying_subs_sub48
http___www.aphref.aph.gov.au_house_committee_ee_bullying_subs_sub48http___www.aphref.aph.gov.au_house_committee_ee_bullying_subs_sub48
http___www.aphref.aph.gov.au_house_committee_ee_bullying_subs_sub48Penny Webster, PhD
 

Viewers also liked (13)

Prakriya ap presentation
Prakriya ap presentationPrakriya ap presentation
Prakriya ap presentation
 
Curriculum Vitae
Curriculum VitaeCurriculum Vitae
Curriculum Vitae
 
NDW July 06 2015
NDW July 06 2015NDW July 06 2015
NDW July 06 2015
 
The Man Behind the Majestic Heli Vincent inc.
The Man Behind the Majestic Heli Vincent inc.The Man Behind the Majestic Heli Vincent inc.
The Man Behind the Majestic Heli Vincent inc.
 
Bunte april 2015 - PAR
Bunte april 2015 - PARBunte april 2015 - PAR
Bunte april 2015 - PAR
 
Business Mentor Perth Balanced Scorecard Presentation 1.7
Business Mentor Perth   Balanced Scorecard Presentation 1.7Business Mentor Perth   Balanced Scorecard Presentation 1.7
Business Mentor Perth Balanced Scorecard Presentation 1.7
 
Business Mentor Perth Balanced Scorecard Presentation 1.6
Business Mentor Perth   Balanced Scorecard Presentation 1.6Business Mentor Perth   Balanced Scorecard Presentation 1.6
Business Mentor Perth Balanced Scorecard Presentation 1.6
 
486 s12-03-io-devices
486 s12-03-io-devices486 s12-03-io-devices
486 s12-03-io-devices
 
Wind energy
Wind energyWind energy
Wind energy
 
HAMZA SHAHID
HAMZA  SHAHIDHAMZA  SHAHID
HAMZA SHAHID
 
De brandende rivier en een biertje Blauwalg
De brandende rivier en een biertje BlauwalgDe brandende rivier en een biertje Blauwalg
De brandende rivier en een biertje Blauwalg
 
Daily Nifty 50 Report
Daily Nifty 50 ReportDaily Nifty 50 Report
Daily Nifty 50 Report
 
http___www.aphref.aph.gov.au_house_committee_ee_bullying_subs_sub48
http___www.aphref.aph.gov.au_house_committee_ee_bullying_subs_sub48http___www.aphref.aph.gov.au_house_committee_ee_bullying_subs_sub48
http___www.aphref.aph.gov.au_house_committee_ee_bullying_subs_sub48
 

Similar to Chapter 3 malik

C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyGrejoJoby1
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic Manzoor ALam
 
Input and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesInput and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesssuserf86fba
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptxDeepasCSE
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and outputOnline
 
Object oriented programming 13 input stream and devices in cpp
Object oriented programming 13 input stream and devices in cppObject oriented programming 13 input stream and devices in cpp
Object oriented programming 13 input stream and devices in cppVaibhav Khanna
 
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docxINPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docxjaggernaoma
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++K Durga Prasad
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in PythonSumit Satam
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxshivam460694
 

Similar to Chapter 3 malik (20)

Input and Output
Input and OutputInput and Output
Input and Output
 
L4.pdf
L4.pdfL4.pdf
L4.pdf
 
Lecture 8- Data Input and Output
Lecture 8- Data Input and OutputLecture 8- Data Input and Output
Lecture 8- Data Input and Output
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
02a fundamental c++ types, arithmetic
02a   fundamental c++ types, arithmetic 02a   fundamental c++ types, arithmetic
02a fundamental c++ types, arithmetic
 
Input and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequencesInput and output basic of c++ programming and escape sequences
Input and output basic of c++ programming and escape sequences
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
FILE OPERATIONS.pptx
FILE OPERATIONS.pptxFILE OPERATIONS.pptx
FILE OPERATIONS.pptx
 
C++ Ch3
C++ Ch3C++ Ch3
C++ Ch3
 
Formatted input and output
Formatted input and outputFormatted input and output
Formatted input and output
 
Object oriented programming 13 input stream and devices in cpp
Object oriented programming 13 input stream and devices in cppObject oriented programming 13 input stream and devices in cpp
Object oriented programming 13 input stream and devices in cpp
 
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docxINPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
INPUT AND OUTPUT PROCESSINGPlease note that the material o.docx
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 
COM1407: Input/ Output Functions
COM1407: Input/ Output FunctionsCOM1407: Input/ Output Functions
COM1407: Input/ Output Functions
 
Basic Concepts in Python
Basic Concepts in PythonBasic Concepts in Python
Basic Concepts in Python
 
Object Oriented Programming with C++
Object Oriented Programming with C++Object Oriented Programming with C++
Object Oriented Programming with C++
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Python Scipy Numpy
Python Scipy NumpyPython Scipy Numpy
Python Scipy Numpy
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 

Recently uploaded

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 

Recently uploaded (20)

Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 

Chapter 3 malik

  • 1. Input and OutputInput and Output Chapter 3Chapter 3
  • 2. 2 Chapter 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
  • 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>