Download presentation
Presentation is loading. Please wait.
Published byAmberly Charles Modified over 9 years ago
1
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 by Bjarne Stroustrup and Jennifer Welch
2
CSCE 121:509-512 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
3
CSCE 121:509-512 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:
4
CSCE 121:509-512 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”
5
CSCE 121:509-512 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”
6
CSCE 121:509-512 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
7
CSCE 121:509-512 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
8
CSCE 121:509-512 Set 10: Input/Output Streams Files 8 General model disk I/O system main memory Files (sequences of bytes) iostreams Objects (of various types)
9
CSCE 121:509-512 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
10
CSCE 121:509-512 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
11
CSCE 121:509-512 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
12
CSCE 121:509-512 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
13
CSCE 121:509-512 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
14
CSCE 121:509-512 Set 10: Input/Output Streams File I/O Example Suppose we are given a file containing temperature data in the format 0 60.7 1 60.6 2 60.3 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
15
CSCE 121:509-512 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
16
CSCE 121:509-512 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
17
CSCE 121:509-512 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
18
CSCE 121:509-512 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
19
CSCE 121:509-512 Set 10: Input/Output Streams Sample Integer Read “Failures” Ended by “terminator character” – 1 2 3 4 5 * – state is fail() Ended by format error – 1 2 3 4 5.6 – state is fail() Ended by “end of file” – 1 2 3 4 5 (no more data in file) – 1 2 3 4 5 Ctrl-Z (Windows) – 1 2 3 4 5 Ctrl-D (Unix) – state is eof() Something really bad – disk format error – state is bad() 19
20
CSCE 121:509-512 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() }
21
CSCE 121:509-512 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
22
CSCE 121:509-512 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
23
CSCE 121:509-512 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
24
CSCE 121:509-512 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
25
CSCE 121:509-512 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
26
CSCE 121:509-512 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
27
CSCE 121:509-512 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
28
CSCE 121:509-512 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
29
CSCE 121:509-512 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
30
CSCE 121:509-512 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
31
CSCE 121:509-512 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
32
CSCE 121:509-512 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
33
CSCE 121:509-512 Set 10: Input/Output Streams Acknowledgments Slides are based on those for the textbook: http://www.stroustrup.com/Programming/10_iostreams.ppt 33
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.