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
 
Advanced+pointers
Advanced+pointersAdvanced+pointers
Advanced+pointers
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 

Viewers also liked

Module 1 a media word lesson 1
Module 1   a media word lesson 1Module 1   a media word lesson 1
Module 1 a media word lesson 1adamleadbeater
 
aviva_newsletter_may_2015_web
aviva_newsletter_may_2015_webaviva_newsletter_may_2015_web
aviva_newsletter_may_2015_webJulie McCloy
 
Dreams and madness
Dreams and madnessDreams and madness
Dreams and madnessAlice Shone
 
Pdn tech-netfilter&iptables-ver2.1.0
Pdn tech-netfilter&iptables-ver2.1.0Pdn tech-netfilter&iptables-ver2.1.0
Pdn tech-netfilter&iptables-ver2.1.0pdnsoftco
 
Castle Leslie Estate
Castle Leslie EstateCastle Leslie Estate
Castle Leslie Estatemeetinireland
 
EDM_IJTIR_Article_201504020
EDM_IJTIR_Article_201504020EDM_IJTIR_Article_201504020
EDM_IJTIR_Article_201504020Ritika Saxena
 
Critical thinking
Critical thinkingCritical thinking
Critical thinkingamkrisha
 
Benford’s law & fraud detection slides
Benford’s  law & fraud detection slidesBenford’s  law & fraud detection slides
Benford’s law & fraud detection slidesSPb_Data_Science
 
Pawel ciecek neuroscience - 2011
Pawel ciecek   neuroscience - 2011Pawel ciecek   neuroscience - 2011
Pawel ciecek neuroscience - 2011Ray Poynter
 
6 в класс
6 в класс6 в класс
6 в классklepa.ru
 

Viewers also liked (19)

Module 1 a media word lesson 1
Module 1   a media word lesson 1Module 1   a media word lesson 1
Module 1 a media word lesson 1
 
aviva_newsletter_may_2015_web
aviva_newsletter_may_2015_webaviva_newsletter_may_2015_web
aviva_newsletter_may_2015_web
 
Dylan Bollinger
Dylan BollingerDylan Bollinger
Dylan Bollinger
 
Ebook progetti is
Ebook progetti isEbook progetti is
Ebook progetti is
 
Dreams and madness
Dreams and madnessDreams and madness
Dreams and madness
 
Pdn tech-netfilter&iptables-ver2.1.0
Pdn tech-netfilter&iptables-ver2.1.0Pdn tech-netfilter&iptables-ver2.1.0
Pdn tech-netfilter&iptables-ver2.1.0
 
Castle Leslie Estate
Castle Leslie EstateCastle Leslie Estate
Castle Leslie Estate
 
EDM_IJTIR_Article_201504020
EDM_IJTIR_Article_201504020EDM_IJTIR_Article_201504020
EDM_IJTIR_Article_201504020
 
CV Jaime Viera Arbelo
CV Jaime Viera ArbeloCV Jaime Viera Arbelo
CV Jaime Viera Arbelo
 
Critical thinking
Critical thinkingCritical thinking
Critical thinking
 
Maldives
MaldivesMaldives
Maldives
 
Benford’s law & fraud detection slides
Benford’s  law & fraud detection slidesBenford’s  law & fraud detection slides
Benford’s law & fraud detection slides
 
Java generics
Java genericsJava generics
Java generics
 
Optimus - Spain Industrial Market 2015
Optimus - Spain Industrial Market 2015Optimus - Spain Industrial Market 2015
Optimus - Spain Industrial Market 2015
 
Optimus - Spain Retail Market 2015
Optimus - Spain Retail Market 2015Optimus - Spain Retail Market 2015
Optimus - Spain Retail Market 2015
 
Optimus - Spain Hotel Market 2015
Optimus - Spain Hotel Market 2015Optimus - Spain Hotel Market 2015
Optimus - Spain Hotel Market 2015
 
Pawel ciecek neuroscience - 2011
Pawel ciecek   neuroscience - 2011Pawel ciecek   neuroscience - 2011
Pawel ciecek neuroscience - 2011
 
6 в класс
6 в класс6 в класс
6 в класс
 
CV Christelle Mitchley
CV Christelle MitchleyCV Christelle Mitchley
CV Christelle Mitchley
 

Similar to CppIOChapter

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 CppIOChapter (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

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 

Recently uploaded (20)

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 

CppIOChapter

  • 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>