CSCE 121:509-512 Introduction to Program Design and Concepts Dr. J. Michael Moore Spring Fall 2016 Set 10: Input/Output Streams 1 Based on slides created.

Slides:



Advertisements
Similar presentations
Chapter 10 Input/Output Streams
Advertisements

CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 7: Errors 1 Based on slides created by Bjarne Stroustrup.
Chapter 10.
Input/Output Main Memory istream ostream Disk Drive Keyboard Scanner Disk Drive Monitor Printer stream = sequence of bytes.
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.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
Chapter 3: Input/Output
Streams, Files. 2 Stream Stream is a sequence of bytes Input stream In input operations, the bytes are transferred from a device to the main memory Output.
CSCE 121: Introduction to Program Design and Concepts J. Michael Moore Fall 2014 Set 11: More Input and Output 1 Based on slides created by Bjarne.
Stream Handling Streams - means flow of data to and from program variables. - We declare the variables in our C++ for holding data temporarily in the memory.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
CSCE 121: Introduction to Program Design and Concepts, Honors Dr. J. Michael Moore Spring 2015 Set 3: Objects, Types, and Values 1 Based on slides.
Chapter 10 Input/Output Streams John Keyser’s Modifications of Slides by Bjarne Stroustrup
C++ for Engineers and Scientists Second Edition Chapter 8 I/O File Streams and Data Files.
File I/O ifstreams and ofstreams Sections 11.1 &
1 Streams In C++, I/O occurs in streams. A stream is a sequence of bytes Each I/O device (e.g. keyboard, mouse, monitor, hard disk, printer, etc.) receives.
1 CS161 Introduction to Computer Science Topic #13.
FILE HANDLING IN C++.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
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.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 10 Input/Output Streams Hartmut Kaiser
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
FILE I/O IN C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 4: Computation 1 Based on slides created by Bjarne Stroustrup.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Chapter 3: Input/Output
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
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.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
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.
Declaring fstream Objects An istream object named cin connects program and keyboard An ostream object named cout connects the program and the screen These.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Files To read a file – We must know its name – We must open it (for reading) – Then we can read – Then we must close it That is typically done implicitly.
24 4/11/98 CSE 143 Stream I/O [Appendix C]. 25 4/11/98 Input/Output Concepts  Concepts should be review!  New syntax, but same fundamental concepts.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 10 Input/Output Streams Hartmut Kaiser
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
CSE 232: Moving Data Within a C++ Program Moving Data Within a C++ Program Input –Getting data from the command line (we’ve looked at this) –Getting data.
CSCE Introduction to Program Design and Concepts J. Michael Moore Spring 2015 Set 6: Miscellaneous 1 Based on slides created by Bjarne Stroustrup.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
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.
Bill Tucker Austin Community College COSC 1315
Chapter 14: Sequential Access Files
Chapter 1.2 Introduction to C++ Programming
ifstreams and ofstreams
Chapter 1.2 Introduction to C++ Programming
Basic Input and Output Operations
Copyright © 2003 Pearson Education, Inc.
File I/O.
Lecture 5A File processing Richard Gesick.
Exceptions with Functions
Chapter 10 Input/Output Streams
IO Overview CSCE 121 J. Michael Moore
Chapter 3: Input/Output
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 10 Input/Output Streams
Fundamental Programming
Reading from and Writing to Files
ifstreams and ofstreams
IO Overview CSCE 121 Strongly influenced by slides created by Bjarne Stroustrup and Jennifer Welch.
Reading from and Writing to Files
Programming Fundamental-1
Presentation transcript:

CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring Fall 2016 Set 10: Input/Output Streams 1 Based on slides created by Bjarne Stroustrup and Jennifer Welch

CSCE 121: Set 10: Input/Output Streams Outline Fundamental I/O concepts Files – opening and closing – reading and writing streams I/O errors Reading a single integer User-defined I/O 2

CSCE 121: Set 10: Input/Output Streams Input and Output 3 input device device driverinput library our program output librarydevice driver output device data source: data destination:

CSCE 121: Set 10: Input/Output Streams The Stream Model An ostream – turns values of various types into character sequences – sends those characters somewhere (console, file, main memory, another computer…) 4 c (1,234) 123 ostream buffer “somewhere”

CSCE 121: Set 10: Input/Output Streams The Stream Model An istream – turns character sequences into values of various types – gets those characters from somewhere (console, file, main memory, another computer,…) 5 c (1,234) 123 istream buffer “somewhere”

CSCE 121: Set 10: Input/Output Streams The Stream Model Supports reading and writing of typed entitites – > (input) plus other operations – type-safe – formatted typically stored as text – but not necessarily, e.g, binary streams extensible – define your own I/O operations for your own types a stream can be attached to any I/O or storage device 6

CSCE 121: Set 10: Input/Output Streams Files Main memory is transient – when power goes off, contents of main memory is lost Use disks, etc. for permanent storage A file is a sequence of bytes in permanent storage – a file has a name – the data in a file has a format We can read and write a file if we know its name and format 7

CSCE 121: Set 10: Input/Output Streams Files 8 General model disk I/O system main memory Files (sequences of bytes) iostreams Objects (of various types)

CSCE 121: Set 10: Input/Output Streams Reading a File 1.Obtain the file’s name 2.Open the file for reading 3.Read from the file 4.Close the file – usually done implicitly Uses a special kind of istream called an ifstream 9

CSCE 121: Set 10: Input/Output Streams Writing a File 1.Name the file 2.Open the file for writing – either an existing file or create a new one 3.Write to the file 4.Close the file – usually done implicitly Uses a special kind of ostream called an ofstream 10

CSCE 121: Set 10: Input/Output Streams Opening a File for Reading cout << “Enter input file name: “; string iname; cin >> iname; ifstream ist {iname}; // or iname.c_str() // ist is a variable of type ifstream; note special // constructor syntax with { and }. if (!ist) error(“Can’t open input file “,iname); // if no error, then variable ist is ultimately // connected to the file whose name is // stored in the variable iname int x; ist >> x; // read from ist using >> (as with cin) 11

CSCE 121: Set 10: Input/Output Streams Opening a File for Writing cout << “Enter inpout file name: “; string oname; cin >> oname; ofstream ost {oname}; // or oname.c_str() // ost is a variable of type ofstream; note special // constructor syntax with { and }. if (!ost) error(“Can’t open output file “,oname); // if no error, then variable ost is ultimately // connected to the file whose name is // stored in the variable oname int x =67; ost << x; // write to ost using << (as with cout) 12

CSCE 121: Set 10: Input/Output Streams Opening and Closing Files File is automatically opened when ifstream or ofstream variable is created File is automatically closed when ifstream or ofstream variable goes out of scope – for example, the function in which the variable is declared returns In rare circumstances, you might need to explicitly open or close a file at other times – you may see older code that does this even when not necessary 13

CSCE 121: Set 10: Input/Output Streams File I/O Example Suppose we are given a file containing temperature data in the format where first number per line is hour of the day (0 through 23) and second number per line is temperature (in Fahrenheit). Task is to reformat the file to be this: (0,60.7) (1,60.6) (2,60.3) 14

CSCE 121: Set 10: Input/Output Streams File I/O Example: Design Use a struct that puts together the hour number and its matching temperature: struct Reading { int hour double temperature; }; Successively obtain readings from input file and store in a vector of Readings Loop through the vector and write out each reading to a new file in the new format 15

CSCE 121: Set 10: Input/Output Streams File I/O Example Details // assuming previous code for opening files and Reading struct vector temps; int hour; double temperature; while (ist >> hour >> temperature) { if (hour < 0 || 23 < hour) error(“hour out of range”); temps.push_back(Reading{hour,temperature}); } for (Reading r : temps) { ost << ‘(‘ << r.hour << ‘,’ << r.temperature << “)\n”; } // See page 354 of textbook for complete code 16

CSCE 121: Set 10: Input/Output Streams I/O Error Handling iostream reduces all errors to one of four states: –good() // the operation succeeded –eof() // we hit the end of the input –fail() // something unexpected happened –bad() // something unexpected and serious happened These 4 are functions that return true under the stated conditions, otherwise false Conditions are indicated by certain bits being set Clear all the bits and return to the good() state with the function –clear() 17

CSCE 121: Set 10: Input/Output Streams I/O Error Handling and Conditions We have been using these C++ idioms: –while (cin >> var) /* while loop body */ –if (!ist) /* report error */ What is going on? – Extraction ( >> ) and insertion ( << ) operators on streams return references to the stream – There is an implicit conversion from a stream object to a boolean (e.g., in the conditions of while and if statements) – The conversion yields true if the stream is good(), and false otherwise 18

CSCE 121: Set 10: Input/Output Streams Sample Integer Read “Failures” Ended by “terminator character” – * – state is fail() Ended by format error – – state is fail() Ended by “end of file” – (no more data in file) – Ctrl-Z (Windows) – Ctrl-D (Unix) – state is eof() Something really bad – disk format error – state is bad() 19

CSCE 121: Set 10: Input/Output Streams I/O Error Handling with Stream States 20 void fill_vector(istream& ist, vector & v, char terminator) // read integers from ist into v until reaching eof() or terminator { int i = 0; while (ist >> i) v.push_back(i); if (ist.eof()) return; // fine: we found end of file if (ist.bad()) error(“ist is bad”); // stream corrupted, get out if (ist.fail()) { // try to clean up, maybe we found terminator ist.clear(); // clear stream state so we can look for terminator char c; ist >> c; // try to read a char if (c != terminator) { // unexpected char (not terminator) ist.unget(); // put character back into stream ist.clear(ios_base::failbit); // set state back to fail() }

CSCE 121: Set 10: Input/Output Streams Throw an Exception for bad() Simplify previous logic by not even worrying about bad() – just throw an exception After defining ifstream ist, indicate that you want an exception thrown if its state ever goes bad() : ist.exceptions(ist.exceptions()|ios_base::badbit); This will cause an exception of type ifstream::failure to be thrown, which you can catch where you like 21

CSCE 121: Set 10: Input/Output Streams Another Example: Reading an Integer in a Range Problem statement: Read in an integer within some range (say, 1 to 10) Deal with – user enters an integer not in range – user enters something of wrong type – user enters nothing Need appropriate prompts to the user See Section 10.7 of textbook for bad solutions 22

CSCE 121: Set 10: Input/Output Streams Reading an Integer in Range Key to having a clean solution to the problem is to break things into logically separate manageable pieces: 1.reading values 2.prompting user for input 3.writing error messages 4.skipping past “bad” input characters 5.testing the input against a range Also aim for generality – don’t hardcode range bounds – don’t hardcode prompts 23

CSCE 121: Set 10: Input/Output Streams Reading an Integer in a Range int get_int(int low, int high, const string& greeting, const string& sorry) { cout << greeting << “ between “ << low << “ and “ << high << endl; while (true) { int n = get_int(); if (low <= n && n <= high) return n; // success cout << sorry << endl; } 24

CSCE 121: Set 10: Input/Output Streams Reading an Integer int get_int() { int n = 0; while (true) { if (cin >> n) return n; // success cout << “Not a number, try again\n”; skip_to_int(); } 25

CSCE 121: Set 10: Input/Output Streams Skipping Bad (non-int) Characters void skip_to_int() // precondition: cin is either fail() or eof() { if (cin.fail() { // found something, but not an int cin.clear(); // we want to look at the characters // why does this for loop not need to increment? for (char ch; cin >> ch; ) { if (isdigit(ch) || ch ==‘-’) { cin.unget(); //put digit back so we can read int return; // if not a digit or – then ignore it and continue } // only remaining option is eof() error(“no input”); } 26

CSCE 121: Set 10: Input/Output Streams Reading an Int in Range: Remaining Issues Error message in get_int() is not parameterized Ideally, utility functions should not have messages hardcoded into them In fact, library functions shouldn’t (directly) write to the user at all – instead throw exceptions, which can contain error messages 27

CSCE 121: Set 10: Input/Output Streams User-Defined Output: operator<<() Must return a reference to an ostream First parameter must be a reference to an ostream Second parameter must be a reference to an object of your type ostream& operator<<(ostream& os, const Date& d) { return os << ‘(‘ << d.year() << ‘,’ << d.month() << ‘,’ << d.day() << ‘)’; } 28

CSCE 121: Set 10: Input/Output Streams Calling User-Defined << void print_out(Date d1, Date d2) { cout << d1; // means operator<<(cout,d1); cout << d1 << d2; // means (cout << d1) << d2; // means (operator<<(cout,d1)) << d2; // means (operator<<((operator<<(cout,d1)),d2); } 29

CSCE 121: Set 10: Input/Output Streams User-Defined Input: operator>>() Must return a reference to an istream First parameter must be a reference to an istream Second parameter must be a reference to an object of your type 30

CSCE 121: Set 10: Input/Output Streams operator>>() Example istream& operator>>(istream& is, Date& dd) // Assume date is in format “(year,month,day)” { int y, d, m; char ch1, ch2, ch3, ch4; is >> ch1 >> y >> ch2 >> m >> ch3 >> d >> ch4; if (!is) return is; // we didn’t get our values; leave if (ch1 != ‘(‘ || ch2 != ‘,’ || ch3 != ‘,’ || ch4 != ‘)’) { // oops: format error is.clear(ios_base::failbit); // set stream state to fail return is; // leave } dd = Date(y,Month(m),d); // update dd via copy assignment return is; // leave with is in good state } 31

CSCE 121: Set 10: Input/Output Streams Calling User-Defined >> //... cout << “Enter a date in format (year,month,date): “; Date d; cin >> d; if (cin) // continue... 32

CSCE 121: Set 10: Input/Output Streams Acknowledgments Slides are based on those for the textbook: 33