1 Simple File I/O Chapter 11 Switch Statement Chapter 12.

Slides:



Advertisements
Similar presentations
Getting Data into Your Program
Advertisements

CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
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.
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
CS-1030 Dr. Mark L. Hornick 1 IOStreams revisited Streams, strings, and files.
File streams Chapter , ,
Chapter 5: Loops and Files.
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.
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.
Program Input and the Software Design Process ROBERT REAVES.
Chapter 3 Interactivity and Expressions CSC 125 Introduction to C++ programming.
Input and Output in Console Mode UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
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.
Chapter 6 Looping.
CS Class 13 Today  File I/O (reading from and writing to files)  Reading until EOF  Formatting output  Nested Loops Announcements  Programming.
File I/O ifstreams and ofstreams Sections 11.1 &
Chapter 9 I/O Streams and Data Files
1 CS161 Introduction to Computer Science Topic #13.
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.
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.
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.
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.
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
Chapter 3: Input/Output
Chapter 3 Working with Batches of Data. Objectives Understand vector class and how it can be used to collect, store and manipulate data. Become familiar.
Loops and Files. 5.1 The Increment and Decrement Operators.
Operating System Using setw and setprecision functions Using setiosflags function Using cin function Programming 1 DCT
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.
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.
File Processing Files are used for data persistance-permanent retention of large amounts of data. Computer store files on secondary storage devices,such.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
1 Programming in C++ Dale/Weems/Headington Chapter 6 Looping.
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.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
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.
Writing to Files and Reading From Files. Writing Data to a File Creating a new file, a.dat or.txt file #include #include // for file writing #include.
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.
CS 1430: Programming in C++ 1. File Input in VS Project Properties Debugging Command Arguments quiz8-1.out We want to know how to do it ourselves, right?
1 Stream Input and Output Read Text, page Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing.
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.
C++ Basic Input and Output (I/O)
EGR 2261 Unit 3 Input/Output Read Malik, Chapter 3.
Copyright © 2003 Pearson Education, Inc.
Chapter 5: Looping Starting Out with C++ Early Objects Eighth Edition
Input and Output Chapter 3.
Today’s Lecture I/O Streams Tools for File I/O
Chapter 3: Input/Output
Chapter 3 Input output.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 4 INPUT AND OUTPUT OBJECTS
File I/O in C++ I.
Formatted Input, Output & File Input, Output
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
Reading Data From and Writing Data To Text Files
C++ Programming Lecture 8 File Processing
File I/O in C++ I.
Presentation transcript:

1 Simple File I/O Chapter 11 Switch Statement Chapter 12

2 Agenda File names and file streams  Intro to Classes and Objects End-of-file Loops Formatting Output Switch statement

3 The need for files in programming Oracle Testing—allows rapid data entry for thorough testing of all branches of code (every if, else, case, etc) Recording Output—maintaining records of program executions Word processing—storing documents that can be edited and revised when a word processor runs

4 File Names and Types A file name should reflect its contents Payroll.dat Students.txt Grades.txt A file’s extension indicates the kind of data the file holds.dat,.txt general program input or output.cpp C++ source file.docMicrosoft word document

5 I/O Streams A stream in C++ is a conduit (pipe) through which data passes Input passes through the istream object and output passes through the ostream object. Input and output are managed by the istream object cin and the ostream object cout The istream class defines the use of the extraction operator ‘ >> ’ (used with cin)

6 Stream Extraction and Insertion #include Input (stream extraction): cin >> // takes data from stream and sticks in variable Output (stream insertion): cout << // takes data from variable and puts into stream Input (Extraction) skips whitespace! ‘\n’, ‘\t’, ‘ ‘, ‘\r’, ‘\v’

7 Input and Output File Streams Input from a file is managed by an ifstream object in the same way that the input from the keyboard is managed by the istream object cin Similarly, output to a file is managed by an ofstream object in the same way that the output to the monitor is managed by the ostream object cout The difference is that ifstream and o fstream objects have to be declared explicitly and initialized with the external name of the file which they manage #include the header file

8 Files: Let’s Use Them #include Declare a file stream variable ifstream inFile;//input file stream ofstream outFile;//output file stream Open the files inFile.open(“MyInput.dat”); outFile.open(“MyOutput.dat”);

9 #include void main() Create a new file stream newfile { ofstream newfile; Connect newfile to the file on disk newfile.open("students.txt"); newfile<<“this is written to the file”; cout<<“this is written to the monitor”; } Output File Stream Example

10 Write a database file, Lab 9 prob 1) char done = 'y'; int acntnum;//an account number float balance;// an account balance ofstream outfile;// a file variable. outfile.open ("accnts.dat"); // prepare database file for writing a) Setting up Output File

11 Lab 9 prob 1) continued // Now input values from keyboardand write to the disk. while (done != 'n') {cout << "enter an accnt number and balance: "; cin >> acntnum >> balance; outfile << acntnum << " " << balance << endl; cout << "another account? enter `y' or `n':"; cin >> done; } Download Lab9 & Try 1) Now! b) Using output file

12 Lab 9 Prob 2) Now Read database file float sum = 0.0; ifstream infile; // a file var. for the input infile.open ("accnts.dat"); //prepare file for reading for (n=0; n<3; n++)// sum 3 accounts... {infile >> acntnum >> balance; sum += balance; } cout << "The total of all accounts is: " << sum ; Same file we wrote to

13 Always Close your Files Don’t forget to close the files when you are done with them infile.close( ); outfile.close( ); Handles any final writing and lets file be re- opened later in program. Put this after all reads/writes are finished (usually right before program or function terminates)

14 Alternative Opening Syntax Instead of Declaring then opening: ifstream infile; infile.open(“accts.dat”); You can Declare and Open in one statement ifstream infile(“accts.dat”); ofstream outFile(“accts.dat”);

15 Agenda File names and file streams Intro to Classes and Objects  End-of-file Loops Formatting Output

16 Intro to Objects and Classes An object is a variable that has functions and data associated with it infile and outfile each have a function named open( ) associated with them infile and outfile use different versions of a function named open One version of open is for input files A different version of open is for output files

17 Calling a Member Function Calling a member function requires first specifying the object containing the function The calling object is separated from the member function by the dot operator Example: inFile. open(“accts.dat"); Calling object Dot operator Member function

18 Classes A type whose variables are objects, is a class ifstream is the type of the infile variable (object) ifstream is a class The class of an object determines its member functions Example: ifstream inputFile, inputData; inputFile.open and inputData.open are the same function but might be given different filenames to open

19 Class Member Functions The member functions an object can use are defined in its class definition The class determines the member functions of the object The class ifstream has an open function Every variable (object) declared of type ifstream has that open function available

20 Agenda File names and file streams Intro to Classes and Objects End-of-file Loops  Formatting Output

21 Other Capabilities of File Streams A File stream object maintains a true/false value that can be tested to check an operation ifstream infile; infile.open(“accts.dat”); if (!infile) {cout<<“file not found”; exit(1); } If open was unsuccessful… This message is displayed And program quits

22 Loop until end-of-file Process indefinite list in a file: infile>>acntnum>>balance; while(infile) { // process last data // get next data infile>>acntnum>>balance; } Check stream status after each read

23 A more compact version Process indefinite list in a file: while(infile>>acntnum>>balance) { // process data } Read data and Check status after each read

24 Agenda File names and file streams Intro to Classes and Objects End-of-file Loops Formatting Output 

25 Tools for Stream Formatting Running Lab 9 Prob 1, if we enter We get an accnts.dat file that looks like this: e+07

26 Formatting Output to Files Remember to #include Use setprecision(2) -- to force 2 digits of precision for all float data Use fixed – to force fixed point formatting (no e-notation allowed) for all following data Use left (-- or right) to justify (line up) on left or right side of column strings look better with left, numbers with right Use setw(10) to output data right justified in a field of 10 spaces Only applies to next data

27 Lab 9 Prob1) With Formatting while (done != 'n') { cout << "enter an account number and balance: "; cin >> acntnum >> balance; outfile<<setprecision(2)<<fixed<< setw(10) << acntnum <<setw(15) << balance << endl; cout << "another account? enter `y' or `n':"; cin >> done; } #include

28 The Result! NOW running Listing 8.1 MODIFIED, if we enter We get an accnts.dat file that looks like this:

Slide 29 Creating Space in Output The setw function specifies the number of spaces for the next item Applies only to the next item of output Example: To print the digit 7 in four spaces use outfile<<setw(4)<< 7 << endl; Three of the spaces will be blank 7 (ios::left)

30 switch Statement Can be used instead of if-else-if switch(expression) { case constant1: statementList1; case constant2: statementList2; … case constantN: statementListN; default: statementList0; }

31 switch in Practice…a menu char choice; cout<<enter P for payroll, E for employee info, Q to quit”<<endl; cin>>choice; switch (choice) { case ‘P’: cout<<“processing payroll”; break; case ‘E’: case ‘e’: cout<<“processing employee”; break; default: cout << “Quitting program”; break; }

32 switch in Practice…ATM menu loop do { menu(); // display menu cin>>choice; switch(choice) { case 'B': balance(userID); break; case 'T‘: totalBalance(); break; default:cout<<"Command notvailable”; } } while(choice !='Q'); Use break to avoid “falling through”

33 Sample Final Exam Problem… 12.what is the exact output of the following program segment? for (int k=0; k<8; k++) switch(k) { case 0: case 7: cout<<"R"; break; case 2: cout<<"I"; break; case 3: cout<<"N"; break; case 4: cout<<"D"; break; default: cout<<"E"; break; }

34 Sample Final Exam Problem…with twist 12.what is the exact output of the following program segment? for (int k=0; k<8; k++) switch(k) { case 0: case 7: cout<<"R";  forgot break case 2: cout<<"I"; break; case 3: cout<<"N";  forgot break case 4: cout<<"D"; break; default: cout<<"E"; break; }

35 Finally !!! … THE END