SlideShare a Scribd company logo
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

PPT
C++ Language
Syed Zaid Irshad
 
PDF
Python unit 2 as per Anna university syllabus
DhivyaSubramaniyam
 
PPTX
Intro to c++
temkin abdlkader
 
PDF
C Programming Tutorial - www.infomtec.com
M-TEC Computer Education
 
PPTX
Unit 2. Elements of C
Ashim Lamichhane
 
PPTX
What is c
Nitesh Saitwal
 
PDF
Lecture 2
Mohamed Zain Allam
 
C++ Language
Syed Zaid Irshad
 
Python unit 2 as per Anna university syllabus
DhivyaSubramaniyam
 
Intro to c++
temkin abdlkader
 
C Programming Tutorial - www.infomtec.com
M-TEC Computer Education
 
Unit 2. Elements of C
Ashim Lamichhane
 
What is c
Nitesh Saitwal
 

What's hot (16)

PPTX
03. Operators Expressions and statements
Intro C# Book
 
PPT
CPU INPUT OUTPUT
Aditya Vaishampayan
 
DOC
Assignment c programming
Icaii Infotech
 
PPTX
C++ theory
Shyam Khant
 
PDF
Input and output in c
Rachana Joshi
 
PPSX
C++ Programming Language
Mohamed Loey
 
PDF
Tutorial on c language programming
Sudheer Kiran
 
PDF
C Programming Assignment
Vijayananda Mohire
 
PPTX
04. Console Input Output
Intro C# Book
 
PPT
Basics of c++ Programming Language
Ahmad Idrees
 
PDF
C programming_MSBTE_Diploma_Pranoti Doke
Pranoti Doke
 
PDF
C++
Shyam Khant
 
PPTX
02. Primitive Data Types and Variables
Intro C# Book
 
PPT
Advanced+pointers
Rubal Bansal
 
PPTX
C Programming Unit-3
Vikram Nandini
 
03. Operators Expressions and statements
Intro C# Book
 
CPU INPUT OUTPUT
Aditya Vaishampayan
 
Assignment c programming
Icaii Infotech
 
C++ theory
Shyam Khant
 
Input and output in c
Rachana Joshi
 
C++ Programming Language
Mohamed Loey
 
Tutorial on c language programming
Sudheer Kiran
 
C Programming Assignment
Vijayananda Mohire
 
04. Console Input Output
Intro C# Book
 
Basics of c++ Programming Language
Ahmad Idrees
 
C programming_MSBTE_Diploma_Pranoti Doke
Pranoti Doke
 
02. Primitive Data Types and Variables
Intro C# Book
 
Advanced+pointers
Rubal Bansal
 
C Programming Unit-3
Vikram Nandini
 
Ad

Viewers also liked (13)

PDF
Check
NikhilP14
 
PPTX
Adult toys for couples
madameclaude0
 
PPT
486 s12-03-io-devices
Oshal Shah
 
PDF
Gate
NikhilP14
 
PDF
Ball
NikhilP14
 
PPT
La investigación histórica
Ossiel Hernández Flores
 
PPTX
oppurtunity
Amar Kohli
 
PPTX
Happy birthday tenzin gyatso
Peter SANDERSON DYKES
 
PDF
aviva_newsletter_may_2015_web
Julie McCloy
 
PDF
mkhedr.cv -4
Mohamed khedr
 
PDF
Globe
NikhilP14
 
DOC
Reglam. de baja y alta 2007
Jhon Wilders Serpa Villena
 
PPTX
ELEN601_Project
Teja Adike
 
Check
NikhilP14
 
Adult toys for couples
madameclaude0
 
486 s12-03-io-devices
Oshal Shah
 
Gate
NikhilP14
 
Ball
NikhilP14
 
La investigación histórica
Ossiel Hernández Flores
 
oppurtunity
Amar Kohli
 
Happy birthday tenzin gyatso
Peter SANDERSON DYKES
 
aviva_newsletter_may_2015_web
Julie McCloy
 
mkhedr.cv -4
Mohamed khedr
 
Globe
NikhilP14
 
Reglam. de baja y alta 2007
Jhon Wilders Serpa Villena
 
ELEN601_Project
Teja Adike
 
Ad

Similar to Chapter 3 malik (20)

PDF
Input and Output
Jason J Pulikkottil
 
PPTX
Object oriented programming 13 input stream and devices in cpp
Vaibhav Khanna
 
PDF
L4.pdf
mohammedaqeel37
 
PDF
Managing I/O in c++
Pranali Chaudhari
 
PDF
Input and output basic of c++ programming and escape sequences
ssuserf86fba
 
PPTX
programming language in c&c++
Haripritha
 
PPTX
FILE OPERATIONS.pptx
DeepasCSE
 
PPT
pengenalan mengenai computer dan programming
aqilahkhairuddin389
 
PPT
cpp input & output system basics
gourav kottawar
 
PDF
Input and output in c++
Asaye Dilbo
 
PDF
C_and_C++_notes.pdf
Tigabu Yaya
 
PPT
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
abdurrahimk182
 
PDF
Chap 3 c++
Widad Jamaluddin
 
PPSX
Getting started with c++.pptx
Akash Baruah
 
PPT
Formatted input and output
Online
 
PPTX
Managing console of I/o operations & working with files
lalithambiga kamaraj
 
PDF
Chap 2 c++
Widad Jamaluddin
 
PPT
Chapter 3 Expressions and Inteactivity
GhulamHussain142878
 
PPTX
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
JessylyneSophia
 
Input and Output
Jason J Pulikkottil
 
Object oriented programming 13 input stream and devices in cpp
Vaibhav Khanna
 
Managing I/O in c++
Pranali Chaudhari
 
Input and output basic of c++ programming and escape sequences
ssuserf86fba
 
programming language in c&c++
Haripritha
 
FILE OPERATIONS.pptx
DeepasCSE
 
pengenalan mengenai computer dan programming
aqilahkhairuddin389
 
cpp input & output system basics
gourav kottawar
 
Input and output in c++
Asaye Dilbo
 
C_and_C++_notes.pdf
Tigabu Yaya
 
CPLUSPLUS UET PESHAWAR BS ELECTRICAL 2ND SEMSTER Lecture02.ppt
abdurrahimk182
 
Chap 3 c++
Widad Jamaluddin
 
Getting started with c++.pptx
Akash Baruah
 
Formatted input and output
Online
 
Managing console of I/o operations & working with files
lalithambiga kamaraj
 
Chap 2 c++
Widad Jamaluddin
 
Chapter 3 Expressions and Inteactivity
GhulamHussain142878
 
KMK1093 CHAPTER 2.kkkpptx KMK1093 CHAPTER 2.kkkpptx
JessylyneSophia
 

Recently uploaded (20)

PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PDF
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
PPTX
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
DOCX
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
DOCX
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
PPTX
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
PPTX
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PPTX
Care of patients with elImination deviation.pptx
AneetaSharma15
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PDF
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
PPTX
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
PPTX
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
PDF
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
PPTX
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
Module 2: Public Health History [Tutorial Slides]
JonathanHallett4
 
How to Track Skills & Contracts Using Odoo 18 Employee
Celine George
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
SAROCES Action-Plan FOR ARAL PROGRAM IN DEPED
Levenmartlacuna1
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
Unit 5: Speech-language and swallowing disorders
JELLA VISHNU DURGA PRASAD
 
BASICS IN COMPUTER APPLICATIONS - UNIT I
suganthim28
 
20250924 Navigating the Future: How to tell the difference between an emergen...
McGuinness Institute
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
Care of patients with elImination deviation.pptx
AneetaSharma15
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
Review of Related Literature & Studies.pdf
Thelma Villaflores
 
A Smarter Way to Think About Choosing a College
Cyndy McDonald
 
HISTORY COLLECTION FOR PSYCHIATRIC PATIENTS.pptx
PoojaSen20
 
Health-The-Ultimate-Treasure (1).pdf/8th class science curiosity /samyans edu...
Sandeep Swamy
 
Sonnet 130_ My Mistress’ Eyes Are Nothing Like the Sun By William Shakespear...
DhatriParmar
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 

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>