Input and Output Chapter 3. 2 Chapter Topics  I/O Streams, Devices  Predefined Functions  Input Failure  Formatting Output  Formatting Tools  File.

Slides:



Advertisements
Similar presentations
CPS120: Introduction to Computer Science INPUT/OUTPUT.
Advertisements

File streams Chapter , ,
1 Lecture 6: Input/Output (II) Introduction to Computer Science Spring 2006.
Lecture 18:Topic: I/O Formatting and Files Dale/Weems/Headington
1 Lecture 5: Input/Output (I) Introduction to Computer Science Spring 2006.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 3: Input/Output.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 3: Input/Output.
Chapter 3: Input/Output
Program Input and the Software Design Process ROBERT REAVES.
Input and Output in Console Mode UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA
CHAPTER 3 INPUT/OUTPUT. In this chapter, you will:  Learn what a stream is and examine input and output streams  Explore how to read data from the standard.
1 Chapter 4 Program Input and the Software Design Process.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 3: Input/Output.
Exposure C++ Chapter VII Program Input and Output.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 3: Input/Output.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 3: Input/Output.
Lecture #5: iostream functions دوال الإدخال والإخراج Dr. Hmood Al-Dossari King Saud University Department of Computer Science 4 March 2012.
TEXT FILES. CIN / COUT REVIEW  We are able to read data from the same line or multiple lines during successive calls.  Remember that the extraction.
Input/Output Sujana Jyothi C++ Workshop Day 2. C++ I/O Basics 2 I/O - Input/Output is one of the first aspects of programming that needs to be mastered:
Chapter 3: Assignment, Formatting, and Interactive Input.
C++ for Engineers and Scientists Second Edition Chapter 3 Assignment, Formatting, and Interactive Input.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
1 Program Input Software Design Chapter 4. 2 You Will Want to Know... Prompting for and reading values into a program. Accessing data from a file. What.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
Chapter 3: Input/Output
Chapter -7 Basic function of Input/output system basics and file processing Stream classes : I/O Streams. A stream is a source or destination for collection.
Operating System Using setw and setprecision functions Using setiosflags function Using cin function Programming 1 DCT
PROGRAM ESSENTIALS. TOKENS  SMALLEST UNITS OF A PROGRAM LANGUAGE  Special Symbols  Mathematical Operators  Punctuation  Word Symbols  Key Words.
Chapter 9: Completing the Basics. In this chapter, you will learn about: – Exception handling – Exceptions and file checking – The string class – Character.
Chapter 3 Assignment, Formatting, and Interactive Input C++ for Engineers and Scientists Third Edition.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
1 Manipulators manipulators are used only in input and output statements endl, fixed, showpoint, setw, and setprecision are manipulators that can be used.
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
Program Input and the Software Design Process ROBERT REAVES.
Input/Output. Objectives In this chapter you will: Learn what a stream is and examine input and output streams Explore how to use the input stream functions.
A FIRST BOOK OF C++ CHAPTER 14 THE STRING CLASS AND EXCEPTION HANDLING.
1 Chapter 4 Program Input and the Software Design Process.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Streams and Files Problem Solving, Abstraction, and Design using.
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
1 Chapter 3 Numeric Types, Expressions, and Output Dale/Weems/Headington.
Chapter 4 Strings and Screen I/O. Objectives Define strings and literals. Explain classes and objects. Use the string class to store strings. Perform.
Chapter 3: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Introduction Every program takes some data as input and generate processed data as out put . It is important to know how to provide the input data and.
Topic 2 Input/Output.
CPS120: Introduction to Computer Science
CPS120: Introduction to Computer Science
EGR 2261 Unit 3 Input/Output Read Malik, Chapter 3.
Chapter 3: Expressions and Interactivity.
Input and Output Chapter 3.
Standard Input/Output Streams
Standard Input/Output Streams
Input/Output Handouts: Quiz 2, Unit 3 practice sheets.
Basic Input and Output C++ programs can read and write information using streams A simple input stream accepts typed data from a keyboard A simple output.
Chapter 3: Input/Output
Introduction to cout / cin
Chapter 3 Input output.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 3: Expressions and Interactivity
Chapter 4 Program Input and the Software Design Process
Formatted Input, Output & File Input, Output
Dale/Weems/Headington Program Input and the Software Design Process
Programming Fundamental-1
Presentation transcript:

Input and Output Chapter 3

2 Chapter Topics  I/O Streams, Devices  Predefined Functions  Input Failure  Formatting Output  Formatting Tools  File I/O  I/O Streams, Devices  Predefined Functions  Input Failure  Formatting Output  Formatting Tools  File I/O

3 I/O Streams, Devices  Input stream A sequence of characters/bytesA sequence of characters/bytes From an input deviceFrom an input device Into the computerInto the computer  Output stream A sequence of characters/bytesA sequence of characters/bytes From the computerFrom the computer To an output deviceTo an output device  Input stream A sequence of characters/bytesA sequence of characters/bytes From an input deviceFrom an input device Into the computerInto the computer  Output stream A sequence of characters/bytesA sequence of characters/bytes From the computerFrom the computer To an output deviceTo an output device

4  Input data is considered to be an endless sequence of characters/bytes coming into a program from an input device (keyboard, file, etc.) Input Streams HI MOM. 7..

5 cin and the Extraction Operator >>  A binary operator Takes two operandsTakes two operands Name of an input stream on the leftName of an input stream on the left cin for standard input from keyboardcin for standard input from keyboard Variable on the rightVariable on the right  Variables can be "cascaded" cin >> amount >> count >> direction;  Variables should generally be simple types  A binary operator Takes two operandsTakes two operands Name of an input stream on the leftName of an input stream on the left cin for standard input from keyboardcin for standard input from keyboard Variable on the rightVariable on the right  Variables can be "cascaded" cin >> amount >> count >> direction;  Variables should generally be simple types

6 The Extraction Operator >>  Enables you to do input with the cin command  Think of the >> as pointing to where the data will end up  C++ able to handle different types of data and multiple inputs correctly  Enables you to do input with the cin command  Think of the >> as pointing to where the data will end up  C++ able to handle different types of data and multiple inputs correctly

7 The Reading Marker  Keeps track of point in the input stream where the computer should continue reading  Extraction >> operator leaves reading marker following last piece of data read  Keeps track of point in the input stream where the computer should continue reading  Extraction >> operator leaves reading marker following last piece of data read … HI MOM. 7..

8 The Reading Marker  During execution of a cin command as long as it keeps finding data, it keeps readingas long as it keeps finding data, it keeps reading when the reading marker hits something not data, it quits readingwhen the reading marker hits something not data, it quits reading  Things in the input stream that cin considers not data spacesspaces tab \ttab \t newline character \n (pressing the RETURN key)newline character \n (pressing the RETURN key) for numeric input, something nonnumericfor numeric input, something nonnumeric  During execution of a cin command as long as it keeps finding data, it keeps readingas long as it keeps finding data, it keeps reading when the reading marker hits something not data, it quits readingwhen the reading marker hits something not data, it quits reading  Things in the input stream that cin considers not data spacesspaces tab \ttab \t newline character \n (pressing the RETURN key)newline character \n (pressing the RETURN key) for numeric input, something nonnumericfor numeric input, something nonnumeric

9 Input to a Simple Variable  char Skips any white space charactersSkips any white space characters Reads one characterReads one character Any other characters in the stream are held for later inputAny other characters in the stream are held for later input  int 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  char Skips any white space charactersSkips any white space characters Reads one characterReads one character Any other characters in the stream are held for later inputAny other characters in the stream are held for later input  int 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 Variable  double (or float) Skips leading white spaceSkips leading white space Reads leading + or –Reads leading + or – Reads numerals and at most one decimal pointReads numerals and at most one decimal point Quits reading when it hits something not numericQuits reading when it hits something not numeric  Note example, page 95  double (or float) Skips leading white spaceSkips leading white space Reads leading + or –Reads leading + or – Reads numerals and at most one decimal pointReads numerals and at most one decimal point Quits reading when it hits something not numericQuits reading when it hits something not numeric  Note example, page 95

11 Predefined Functions  Function in a computer language is similar to concept of a function in mathematics The function is sent value(s)The function is sent value(s) Called "arguments" or "parameters"Called "arguments" or "parameters" It manipulates the valueIt manipulates the value It returns a valueIt returns a value  Some functions "do a task"  Function in a computer language is similar to concept of a function in mathematics The function is sent value(s)The function is sent value(s) Called "arguments" or "parameters"Called "arguments" or "parameters" It manipulates the valueIt manipulates the value It returns a valueIt returns a value  Some functions "do a task"

12 Reading cString Data with cin  Keyboard response of two words (separated by a space) causes the cin command to quit reading the space is considered nondata (in spite of our intent)the space is considered nondata (in spite of our intent)  Keyboard response of two words (separated by a space) causes the cin command to quit reading the space is considered nondata (in spite of our intent)the space is considered nondata (in spite of our intent) ???

13 Reading cString Data  The getline ( ) function will allow the programmer to access all the characters char char Array variable Length (max number of characters) Character which terminates read

14 cin and the get Function  Syntax: cin.get(varChar);  Example cin.get (chVal); chVal is the parameterchVal is the parameter the. get function retrieves a character from the keyboardthe. get function retrieves a character from the keyboard stores the character in chValstores the character in chVal  Syntax: cin.get(varChar);  Example cin.get (chVal); chVal is the parameterchVal is the parameter the. get function retrieves a character from the keyboardthe. get function retrieves a character from the keyboard stores the character in chValstores the character in chVal

15 cin and the ignore Function  Syntax: cin.ignore (intValue, charVal);  Example: cin.ignore (10,'\n')  The ignore function causes characters in the input stream to be ignore d (discarded) In this example for 10 characters … or …In this example for 10 characters … or … Until a newline character occursUntil a newline character occurs It also discards the newline characterIt also discards the newline character  Syntax: cin.ignore (intValue, charVal);  Example: cin.ignore (10,'\n')  The ignore function causes characters in the input stream to be ignore d (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)

16 Using the getline( )  Problem : the getline( ) quits reading when it finds a newline Suppose you have terminated previous input with the key (newline still in input stream)Suppose you have terminated previous input with the key (newline still in input stream) getline ( ) finds the newline immediately and declares its task finishedgetline ( ) finds the newline immediately and declares its task finished we must somehow discard the newline in the input streamwe must somehow discard the newline in the input stream  Problem : the getline( ) quits reading when it finds a newline Suppose you have terminated previous input with the key (newline still in input stream)Suppose you have terminated previous input with the key (newline still in input stream) getline ( ) finds the newline immediately and declares its task finishedgetline ( ) finds the newline immediately and declares its task finished we must somehow discard the newline in the input streamwe must somehow discard the newline in the input stream ???

17 Using the ignore( )  Solution : the ignore( ) command  Tells the program to skip either the next 10 characters or until it reaches a newline whichever comes firstwhichever comes first  This effectively discards the newline  Solution : the ignore( ) command  Tells the program to skip either the next 10 characters or until it reaches a newline whichever comes firstwhichever comes first  This effectively discards the newline

18 Input Failure  Happens when value in the input stream is invalid for the variable int x, y; cin >> x >> y; // Enter B 37  Value of 'B' not valid for an int  View example example  Happens when value in the input stream is invalid for the variable int x, y; cin >> x >> y; // Enter B 37  Value of 'B' not valid for an int  View example example When an input stream fails system ignores all further I/O

19 The clear Function  Use the clear to return the input stream to a working state  Example look for cin.clear() cin.ignore (200,'\n'); // to empty out input stream Example  Use the clear to return the input stream to a working state  Example look for cin.clear() cin.ignore (200,'\n'); // to empty out input stream Example

20 Formatting Output  Producing proper output in the proper format 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 manipulators  Syntax: cout << manipulator << expression …  Producing proper output in the proper format 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 manipulators  Syntax: cout << manipulator << expression …

21ManipulatorsManipulators  Must first of all #include  Must first of all #include  For decimal precision use cout << setprecision (n) << …  To output floating point numbers in fixed decimal format use cout << fixed << …  To force decimal zeros to show cout << showpoint << …  Must first of all #include  Must first of all #include  For decimal precision use cout << setprecision (n) << …  To output floating point numbers in fixed decimal format use cout << fixed << …  To force decimal zeros to show cout << showpoint << …

22ManipulatorsManipulators  To specify right justification in a specified number of blanks use cout << setw(n) << …  If the number of blanks required to print the expression exceeds specified size Size is ignoredSize is ignored  Problem – print series of names left justified followed by right justified numbers Osgood Smart 1.23 Joe Schmo  To specify right justification in a specified number of blanks use cout << setw(n) << …  If the number of blanks required to print the expression exceeds specified size Size is ignoredSize is ignored  Problem – print series of names left justified followed by right justified numbers Osgood Smart 1.23 Joe Schmo Names are of different length Need variable number of spaces

23ManipulatorsManipulators  Print name, then variable number of spaces using the setw( )  Example cout << showpoint << fixed ; cout << name << setw( 25 - strlen(name))<<" "; cout << setw (8) << setprecision(2) << amt;  Print name, then variable number of spaces using the setw( )  Example cout << showpoint << fixed ; cout << name << setw( 25 - strlen(name))<<" "; cout << setw (8) << setprecision(2) << amt;

24 Formatting Tools  Possible to specify a character to fill leading spaces cout.fill ('*'); cout << setw(10) << setprecision(2); cout << pmtAmount ;  Result *****12.34  Possible to specify a character to fill leading spaces cout.fill ('*'); cout << setw(10) << setprecision(2); cout << pmtAmount ;  Result *****12.34

25 File I/O  Previous discussion has considered input from 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: An area of secondary storage used to hold information  Keyboard I/O #include  Keyboard I/O #include  File I/O #include  File I/O #include  Previous discussion has considered input from 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: An area of secondary storage used to hold information  Keyboard I/O #include  Keyboard I/O #include  File I/O #include  File I/O #include

26 File I/O  Requirements to do file I/O 1. #include 1. #include 2.Declare a file stream variable ifstream or ofstream 3.Open the file – use the command whateverFile.open("filename.xxx"); 4.Use the stream variable with >> or > or << 5.Close the file whateverFile.close();  Requirements to do file I/O 1. #include 1. #include 2.Declare a file stream variable ifstream or ofstream 3.Open the file – use the command whateverFile.open("filename.xxx"); 4.Use the stream variable with >> or > or << 5.Close the file whateverFile.close();

27 File Open Modes  In some situations you must specify one or more modes for the file  Syntax: fileVariable.open("filename.xxx", fileOpenMode);  In some situations you must specify one or more modes for the file  Syntax: fileVariable.open("filename.xxx", fileOpenMode);

28 Using Files in Programs  Specify #include header file  Declare instance of file to be used  Prepare for access with.open( ) command  Use name of file in place of cin or cout  Specify #include header file  Declare instance of file to be used  Prepare for access with.open( ) command  Use name of file in place of cin or cout file name on disk #include