Streams, Files, and Formatting Chapter 8. 2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams.

Slides:



Advertisements
Similar presentations
File Input/Output. External Files Batch –Requires use of data files (save to disk) –Batch can be run during off peak use –allows things to be complete.
Advertisements

CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
File streams Chapter , ,
C++ Review. 2 Outline C++ basic features Programming paradigm and statement syntax Class definitions Data members, methods, constructor, destructor Pointers,
File I/O. COMP104 Lecture 20 / Slide 2 Using Input/Output Files * A computer file n is stored on a secondary storage device (e.g., disk) n is permanent.
File I/O. COMP104 Lecture 20 / Slide 2 Using Input/Output Files (Review) * A computer file n is stored secondary storage devices (hard drive, CD) n can.
File I/O. COMP104 File I/O / Slide 2 Using Input/Output Files * A computer file n is stored on a secondary storage device (e.g., disk) n is permanent.
CS-212 C++ I/O Dick Steflik. C++ I/O Modeled after UNIX’s concept of a “stream” –conceptionally a stream is a continuous flow of characters/bytes from.
1 Lecture 19 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
Lecture 18:Topic: I/O Formatting and Files Dale/Weems/Headington
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
16/24/2015 1:00 AM6/24/2015 1:00 AM6/24/2015 1:00 AMStreams and Files All the data used in our programs so far has been entered through the keyboard and.
C++ plus. 2 Goals Some general C++ tips 3 C++ Tips is header file for a library that defines three stream objects Keyboard an istream object named cin.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 3: Input/Output.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
CS 117 Spring 2002 Using Files Hanly: Chapter 9, some in Chapter 4 Freidman-Koffman: Chapter 8, iomanip in Chapter 5.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 27P. 1Winter Quarter I/O Manipulation Lecture.
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.
Program Input and the Software Design Process ROBERT REAVES.
Streams, Files, and Formatting Chapter Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams.
Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA
1 Chapter 4 Program Input and the Software Design Process.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
You gotta be cool. Stream Stream Output Stream Input Unformatted I/O with read, gcount and write Stream Manipulators Stream Format States Stream Error.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
File I/O ifstreams and ofstreams Sections 11.1 &
File I/O ifstreams and ofstreams. Some istream Operations istream function Description cin >> ch; Extract next non-whitespace character from cin and store.
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.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
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.
CSE 332: C++ IO We’ve Looked at Basic Input and Output Already How to move data into and out of a program –Using argc and argv to pass command line args.
Lecture Contents I/O Streams. –Input/output streams. –Unformatted vs formatted streams. –Stream manipulators. –Stream error state. –Stream tying. –Examples.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
Disk Files for I/O your variable (of type ifstream) your variable (of type ofstream) disk file “myInfile.dat” disk file “myOut.dat” executing program input.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 21 - C++ Stream Input/Output Basics Outline 21.1Introduction 21.2Streams Iostream Library.
Chapter 3: Input/Output
C++ Review H.O.#3 COMP 171 Spring C++ review2 Outline ◈ C++ basic features Programming paradigm and statement syntax ◈ Class definitions Data members,
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.
Input/Output CSci 588: Data Structures, Algorithms and Software Design Fall 2011 All material not from online sources copyright © Travis Desell, 2011
Streams One of the themes of this course is that everything can be reduced to simple (and similiar) concepts. Streams are one example. Keyboard and Screen.
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.
Lecture 27: File Input/Output Processing. 2 Lecture Contents: t Input/Output files t Text files and Binary files t File access t Standard Input/Output.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Input/Output in C++ C++ iostream.h instead of stdio.h Why change? –Input/output routines in iostream can be extended to new types declared by the user.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Streams and Files Problem Solving, Abstraction, and Design using.
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.
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.
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
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.
Programming II I/O Streams and Data Files 1(c) Asma AlOsaimi.
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.
ifstreams and ofstreams
Chapter 2 part #3 C++ Input / Output
C++ Review Comp 171, Fall 2006.
Standard Input/Output Streams
Standard Input/Output Streams
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.
Today’s Lecture I/O Streams Tools for File I/O
No I/O is built into C++ instead, a library provides input stream and output stream Keyboard Screen executing program istream ostream 1.
Chapter 3 Input output.
File I/O.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 4 Program Input and the Software Design Process
Chapter 2 part #3 C++ Input / Output
C++ Programming Lecture 8 File Processing
ifstreams and ofstreams
Presentation transcript:

Streams, Files, and Formatting Chapter 8

2 8.1 Standard Input/Output Streams t Stream is a sequence of characters t Working with cin and cout t Streams convert internal representations to character streams t >> input operator (extractor) t << output operator (inserter) t Streams have no fixed size

3 Reading Data >> t Leading white space skipped t also skipped t Until first character is located cin >> ch; t Also read character plus white space as a character –get and put functions

4 CountChars.cpp // File: CountChars.cpp // Counts the number of characters and lines in // a file #include using namespace std; #define ENDFILE "CTRL-D" // CTRL-Z for DOS

5 CountChars.cpp int main() { const char NWLN = '\n'; // newline character char next; int charCount; int totalChars; int lineCount; lineCount = 0; totalChars = 0;

6 CountChars.cpp cout << "Enter a line or press " << ENDFILE << ": "; while (cin.get(next)) { charCount = 0; while (next != NWLN && !cin.eof()) { cout.put(next); charCount++; totalChars++; cin.get(next); } // end inner while

7 CountChars.cpp cout.put(NWLN); lineCount++; cout << "Number of characters in line " << lineCount << " is " << charCount << endl; cout << "Enter a line or press " << ENDFILE << ": "; } // end outer while cout << endl << endl << "Number of lines processed is " << lineCount << endl;

8 CountChars.cpp cout << "Total number of characters is " << totalChars << endl; return 0; } Example of a user session: Enter a line or press CTRL-D: line one. Line one. Number of characters is 9 Enter a line or press CTRL-D: line four. Line four. Number of characters is 10 Enter a line or press CTRL-D: CTRL-D Number of lines processed is 2 Total number of characters is 19

9 Stream Functions t stream.open(fname): opens a file stream t stream.get(ch): extracts one character from stream t stream.put(ch): inserts one character into stream t stream.close(): closes an opened file stream t stream.eof(): return true if end of stream is reached and false otherwise t stream.fail(): returns true if a precedent open has failed and false otherwise

External Files t Batch processing –Read data from a file (not from keyboard)  data can be examined  don’t need to retype data when you rerun program –Requires use of data files (save to disk) –Batch can be run during off peak use –allows things to be complete at start of day –Helpful is to echo-print (on the screen) read data t Interactive processing –Real time systems –Ok for smaller programs –Programs that complete quickly

11 Files t Naming (system-dependent) –Directory name e.g. /Myfiles/ –File name e.g. Payroll.txt –Extensions:.cc.dat.out.in.txt t How to attach files to the stream –stream object –external file name –internal name –open t Additional functions as part of fstream class

12 Files t Declare the stream to be processed need to #include ifstreamins;// input stream ofstream outs;// output stream t Need to open the files ins.open (inFileName); outs.open (outFileName);

13 Files t #define associates the name of the stream with the actual file name  You can directly give file names t fail() function - returns true (nonzero) if file fails to open t Program CopyFile.cpp demonstrates the use of the other fstream functions –get, put, close and eof

14 CopyFile.cpp // File: CopyFile.cpp // Copies file InData.txt to file OutData.txt #include using namespace std; // Associate stream objects with external file // names #define inFile "InData.txt" #define outFile "OutData.txt"

15 CopyFile.cpp // Functions used... // Copies one line of text int copyLine(ifstream&, ofstream&); int main() { // Local data... int lineCount; ifstream ins; ofstream outs;

16 CopyFile.cpp // Open input and output file, exit on any // error. ins.open(inFile); if (ins.fail ()) { cerr << "*** ERROR: Cannot open " << inFile << " for input." << endl; return EXIT_FAILURE;// failure return } // end if

17 CopyFile.cpp outs.open(outFile); if (outs.fail()) { cerr << "*** ERROR: Cannot open " << outFile << " for output." << endl; return EXIT_FAILURE;// failure return } // end if // Copy each character from inData to outData. lineCount = 0; do {

18 CopyFile.cpp if (copyLine(ins, outs) != 0) lineCount++; } while (!ins.eof()); // Display a message on the screen. cout << "Input file copied to output file." << endl; cout << lineCount << " lines copied." << endl; ins.close(); outs.close(); return 0; // successful return }

19 CopyFile.cpp // Copy one line of text from one file to another // Pre: ins is opened for input and outs for // output. // Post: Next line of ins is written to outs. // The last character processed from // ins is ; // the last character written to outs // is. // Returns: The number of characters copied. int copyLine (ifstream& ins, ofstream& outs) {

20 CopyFile.cpp // Local data... const char NWLN = '\n'; char nextCh; int charCount = 0; // Copy all data characters from stream ins to // stream outs. ins.get(nextCh); while ((nextCh != NWLN) && !ins.eof()) { outs.put(nextCh); charCount++;

21 CopyFile.cpp ins.get (nextCh); } // end while // If last character read was NWLN write it // to outs. if (!ins.eof()) { outs.put(NWLN); charCount++; } return charCount; } // end copyLine

22 CopyFile.cpp Program Output Input file copied to output file. 37 lines copied.

23 File Processing t Newline character eof() function returns a False if file is not empty while ( ! ins.eof()) { do stuff } t Could have used getline(): string line; linCount = 0; getline(ins, line); while(line.lentgh() != 0) { lineCount++; outs << line << endl; getline(ins, line); }

Using External File Functions t Payroll Case Study Program 1: computes salary using hours and rate Input file: e.g. Adam Smith Thomas New Ayisha Martin Output file: e.g. Adam Smith$ Thomas New$ Ayisha Martin$ Program 2: (not handled here) Does further processing on output file of program 1

25 Payroll Case Structure Chart processEmp

26 ProcessEmp Structure Chart

27 Payroll.cpp // File: Payroll.cpp // Creates a company employee payroll file // computes total company payroll amount #include #include "money.h" #include "money.cpp" using namespace std;

28 Payroll.cpp // Associate streams with external file names #define inFile "EmpFile.txt" // employee file #define outFile "Salary.txt" // payroll file // Functions used... // PROCESS ALL EMPLOYEES AND COMPUTE TOTAL money processEmp(istream&, ostream&); int main() { ifstream eds; ofstream pds; money totalPayroll;

29 Payroll.cpp // Prepare files. eds.open(inFile); if (eds.fail ()) { cerr << "*** ERROR: Cannot open " << inFile << " for input." << endl; return EXIT_FAILURE;// failure return } pds.open(outFile); if (pds.fail()) {

30 Payroll.cpp cerr << "***ERROR: Cannot open " << outFile << " for output." << endl; eds.close(); return EXIT_FAILURE; // failure return } // Process all employees and compute total // payroll. totalPayroll = processEmp(eds, pds); // Display result. cout << "Total payroll is " << totalPayroll << endl;

31 Payroll.cpp // Close files. eds.close(); pds.close(); return 0; }

32 Payroll.cpp // Insert processEmp here. // Process all employees and compute total // payroll amount // Pre: eds and pds are prepared for // input/output. // Post: Employee names and salaries are // written from eds to pds // and the sum of their salaries is returned. // Returns: Total company payroll money processEmp (istream& eds, ostream& pds) {

33 Payroll.cpp string firstName; string lastName; float hours; // input: hoursWorked money rate; // input: hourly rate money salary; // output: gross salary money payroll; // return value - total company payroll payroll = 0.0; // Read first employee's data record. eds >> firstName >> lastName >> hours >> rate;

34 Payroll.cpp while (!eds.eof()) { salary = hours * rate; pds << firstName << “ “ <<lastName << “ “ << salary << endl; payroll += salary; // Read next employee's data record. eds >> firstName >> lastName >> hours >> rate; } // end while return payroll; } // end processEmp

35 PayrollFile.cpp Program Output Total payroll is $677.38

More on Reading String Data t Getline - could be used to process an entire line of data t Use # as a delimiter character getline (eds, name, ‘#’); t Advance the newline getline (eds, name, ‘\n’); t Use care when choosing cin, get or getline

37 Getline() and Ignore() t getline(istream& in, string& s) Reads a line from input stream in and stores it in s t getline(istream& in, string& s, char delimiter) Reads all characters up to ‘delimiter’ and stores them in s (delimiter is read but not stored in s!) t ins.ignore(int n, char delimiter) Extracts (but not store) up to n characters from input stream ins until the first ‘delimiter’ character is encountered. Delimiter is extracted but not stored

Input/Output Manipulators t Chapter 5 covered setw width t Also endl has been introduced t boolalpha has been also used to get ‘true’ and ‘false’ from keyboard t Can be used with the cout and << t #include when using manipulators t Can be used with external files like cin and cout

39 I/O Manipulators t setw(int n): set the width of the next output t setprecesion(int n): sets the precision for (float) numbers (default is 6) t boolalpha: enables true/false for I/O t noboolalpha: disable previous operation t fixed: decimal notation of floats t scientific: scientific notation of floats t showpoint: display decimal point also for integers t noshowpoint: undo previous operation t left: left-adjust output in field t right: right-adjust (default) t skipws: skip white spaces on input (default) t noskipws: undo previous operation

40 Formatting with State Flags t Depending on the setiosflags or unsetiosflags –Output can be controlled by other format state flag –Flags are enumerated types t ios::flagname t Flags e.g.: –boolalpha, fixed, left, right, showpoint etc t Examples: cin.setf(ios::boolalpha); cout.setf(ios::boolalpha);

Common Programming Errors t Connecting streams and external files –Declare stream object and open the file t Watch use of while loops when processing –Test values see what you actually have t Reading past the eof t White space t Newline character t Formatting via flags