What we will learn about this week:

Similar documents
Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Simple File I/O.

Chapter 12. Streams and File I/O

File Input / Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #9

Streams and Basic File I/O Tools for Stream I/O Character I/O Inheritance

File I/O CS 16: Solving Problems with Computers I Lecture #9

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

File Input/Output Streams in C++ CS 16: Solving Problems with Computers I Lecture #10

CS2141 Software Development using C/C++ Stream I/O

Programming in C/C

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

Lecture 3. Input and Output. Review from last week. Variable - place to store data in memory. identified by a name should be meaningful Has a type-

I/O Streams and Standard I/O Devices (cont d.)

C++ Input/Output: Streams

Programming in C/C

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

Strings and Streams. Professor Hugh C. Lauer CS-2303, System Programming Concepts

Engineering Problem Solving with C++, Etter/Ingber

We will exclusively use streams for input and output of data. Intro Programming in C++

Programming in C/C

Setting Justification

Week 3: File I/O and Formatting 3.7 Formatting Output

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

File I/O and String Manipula3ons CS 16: Solving Problems with Computers I Lecture #11

UEE1303(1070) S 12 Object-Oriented Programming in C++

Chapter 2. Outline. Simple C++ Programs

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

What will happen if the user presses <enter> after every input? Will all work like below? Enter the values of x, y, z: Result: The sum is 17.

Why Is Repetition Needed?

File I/O Christian Schumacher, Info1 D-MAVT 2013

More on File I/O Strings in C++ CS 16: Solving Problems with Computers I Lecture #10

Chapter 3 - Notes Input/Output

Lab 6. Review of Variables, Formatting & Loops By: Dr. John Abraham, Professor, UTPA

Input and Output. Data Processing Course, I. Hrivnacova, IPN Orsay

Introduction to Programming EC-105. Lecture 2

Getting started with C++ (Part 2)

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

Chapter 14 Sequential Access Files

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

READ THIS NOW! Failure to read and follow the instructions below may result in severe penalties. Do not start the test until instructed to do so!

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Introduction to C++ (Extensions to C)

Streams - Object input and output in C++

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

CSCS 261 Programming Concepts Exam 1 Fall EXAM 1 VERSION 1 Fall Points. Absolutely no electronic devices may be used during this exam.

Chapter 21 - C++ Stream Input/Output

Fundamentals of Programming CS-110. Lecture 2

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

Reading from and Writing to Files. Files (3.12) Steps to Using Files. Section 3.12 & 13.1 & Data stored in variables is temporary

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Strings and Stream I/O

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

Characters, c-strings, and the string Class. CS 1: Problem Solving & Program Design Using C++

Software Design & Programming I

Chapter 21 - C++ Stream Input/Output

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 7. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

CPE Summer 2015 Exam I (150 pts) June 18, 2015

C++ Input/Output Chapter 4 Topics

READ THIS NOW! Do not start the test until instructed to do so!

! A literal represents a constant value used in a. ! Numbers: 0, 34, , -1.8e12, etc. ! Characters: 'A', 'z', '!', '5', etc.

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

Object-oriented Programming for Automation & Robotics Carsten Gutwenger LS 11 Algorithm Engineering

PROGRAMMING EXAMPLE: Checking Account Balance

C++ Programming Lecture 10 File Processing

Lab # 02. Basic Elements of C++ _ Part1

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

ENGI 1020 Introduction to Computer Programming R E Z A S H A H I D I J U L Y 2 6,

Chapter 3: Input/Output

I BSc(IT) [ Batch] Semester II Core: Object Oriented Programming With C plus plus - 212A Multiple Choice Questions.

Input/Output Streams: Customizing

COMP322 - Introduction to C++

int n = 10; int sum = 10; while (n > 1) { sum = sum + n; n--; } cout << "The sum of the integers 1 to 10 is " << sum << endl;

String Variables and Output/Input. Adding Strings and Literals to Your Programming Skills and output/input formatting

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

! A program is a set of instructions that the. ! It must be translated. ! Variable: portion of memory that stores a value. char

Chapter 3. Numeric Types, Expressions, and Output

WARM UP LESSONS BARE BASICS

Objects and streams and files CS427: Elements of Software Engineering

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

Introduction to Algorithms and Data Structures. Lecture 6 - Stringing Along - Character and String Manipulation

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Understanding main() function Input/Output Streams

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

by Pearson Education, Inc. All Rights Reserved. 2

Overview. - General Data Types - Categories of Words. - Define Before Use. - The Three S s. - End of Statement - My First Program

C++ for Python Programmers

Computer Programming : C++

CSCI 1061U Programming Workshop 2. C++ Basics

Chapter 15 - C++ As A "Better C"

Definition Matching (10 Points)

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Chapter void Test( int, int, int ); // Function prototype int main() // Function heading { int h; // Local variable

THE INTEGER DATA TYPES. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Transcription:

What we will learn about this week: Streams Basic file I/O Tools for Stream I/O Manipulators Character I/O Get and Put EOF function Pre-defined character functions Objects 1

I/O Streams as an Introduction to Objects and Classes Input refers to data flowing INTO your program. Output refers to data flowing OUT OF your program. Input can be taken from the keyboard or a file. Output can be sent to the screen or to a file Input is transferred to a C++ program from either a file or the keyboard by means of an input stream. Output is transferred from a C++ program to the screen or to a file by means of a output stream. Streams are objects defined in the Standard Library s header files <iostream> and <fstream>. 2

I/O to/from Files We will learn to take input from a file and send output to a file. Files allow you to store the data permanently. Files can be used over and over by many programs. Files allow for large amounts of data. 3

File I/O When a program takes data from a file, we say the program is reading from the file. When a program sends output to a file, we say the program is writing to the file. A stream is a flow of characters or other data. In C++ a stream is a special kind of variable known as an object. cin and cout are objects predefined in the iostream library. File streams, like other variables, must be declared by the programmer as needed. 4 4

Defining Streams Defined in fstream library type ifstream input file stream type ofstream output file stream examples: ifstream in_stream; // defines input stream ofstream out_stream; // defines output stream 5

Connecting Streams to Files In the example: in_stream.open ( infile.dat ); // infile.dat must exist on your system out_stream.open ( outfile.dat ); // outfile.dat will be created. This calls the function open. The file stream in_stream is said to be open for reading, and the file stream out_stream is said to be open for writing. This is new! You didn t have to do this for cin and cout. 6 6

File I/O Once we have declared the file variables, in_stream and out_stream, and connected them to files on our system, we can then take input from in_stream and send output to out_stream in exactly the same manner as we have for cin and cout. Examples: #include <fstream>... // appropriate declarations and open statements int one_number, another_number; in_stream >> one_number >> another_number;... out_stream << one_number: << one_number << another_number: << another_number; 7 7

File I/O Every file should be closed when your program is through fetching input or sending output to the file. This is done with the close() function. Example: in_stream.close(): out_stream.close(); Note that the close function takes no arguments. If your program terminates normally, the system will close the arguments. If the program does not terminate normally, this might not happen. File corruption is a real possibility. If you want to save output in a file and read it later, the you must close the file before opening it the second time for reading. 8 8

Display 5.1 page 205 //Reads three numbers from the file infile.dat, sums the numbers, //and writes the sum to the file outfile.dat. //(A better version of this program will be given in Display 5.2.) #include <fstream> int main( ) { using namespace std; ifstream in_stream; ofstream out_stream; in_stream.open("infile.dat"); out_stream.open("outfile.dat"); int first, second, third; in_stream >> first >> second >> third; out_stream << "The sum of the first 3\n" << "numbers in infile.dat\n" << "is " << (first + second + third) << endl; infile.dat 1 2 3 4 outfile.dat The sum of the first 3 numbers in infile.dat is 6 } in_stream.close( ); out_stream.close( ); return 0; 9

Introduction to Classes and Objects Consider the code fragment: #include <fstream>... ifstream in_stream; ostream out_stream; in_stream.open ( infile.dat ); out_stream.open ( outfile.dat );... in_stream.close(): out_stream. close(); Here the streams in_stream and out_stream are objects. An object is a variable that has functions as well as data associated with it. The functions open and close are associated with in_stream and out_stream, as well as the stream data and file data. 10 10

Member Functions Consider the code fragment: #include <fstream>... ifstream in_stream; ostream out_stream; in_stream.open ( infile.dat ); out_stream.open ( outfile.dat );... in_stream.close(); out_stream. close(); The functions and data associated with an object are refered to as members of the object. Functions associated with the object are called member functions. Data associated with the object are called data members. 11 11

Summary of Classes and Objects An object is a variable that has functions associated with it. Functions associated with an object are called member functions. A class is a type whose variables are objects. The object s class determines which member functions the object has. Specify the function by writing the object name, dot operator(.), the function name. Syntax for calling a member function: Calling_Object.member_function(Argument_List); 12 12

Programming Tip Checking that a file was opened successfully A very common error is attempting to open a file for reading where the file does not exist. The member function open fails then. (Except in Microsoft where it may create a file.) Your program must test for this failure, and in the event of failure, manage the error. Use the istream member function fail to test for open failure: in_stream.fail(); This function returns a bool value that is true if the stream is in a fail state, and false otherwise. Example: #include <cstdlib> // for the predefined exit(1); library function... in_stream.open( infile.dat ); if(in_stream.fail()) { cout << Input file opening failed. \n ; exit(1); // Predefined function quits the program. } 13 13

The exit Statement The exit statement is written #include <cstdlib> // exit is defined here using namespace std; // to gain access to the names exit(integer_value); // to exit the program When the exit statement is executed, the program ends immediately. By convention, 1 is used as an argument to exit to signal an error. By convention, 0 is used to signal a normal successful completion of the program. (Use of other values is implementation defined.) The exit is defined in the cstdlib library header file, so any use requires #include <cstdlib> a directive to gain access to the names 14

Display 5.2 File I/O with Checks on open (1 of 2) - Page 210 //Reads three numbers from the file infile.dat, sums the numbers, //and writes the sum to the file outfile.dat. #include <fstream> #include <iostream> #include <cstdlib> int main( ) { using namespace std; ifstream in_stream; ofstream out_stream; in_stream.open("infile.dat"); if (in_stream.fail( )) { cout << "Input file opening failed.\n"; exit(1); } out_stream.open("outfile.dat"); if (out_stream.fail( )) { cout << "Output file opening failed.\n"; exit(1); } 15

Display 5.2 File I/O with Checks on open (2 of 2) int first, second, third; in_stream >> first >> second >> third; out_stream << "The sum of the first 3\n" << "numbers in infile.dat\n" << "is " << (first + second + third) << endl; in_stream.close( ); out_stream.close( ); } return 0; 16

Summary of File I/O Statements Input in this code comes from a file with the directory name infile.dat and output goes to a file outfile.dat Put the following include directive in your program file: #include <fstream> // for file i/o #include <iostream> // for screen/keyboard i/o #include <cstdlib> // for exit Choose a stream name for the input the stream, such as in_stream. Declare it to be a variable of type ifstream: using namespace std; ifstream in_stream; ofstream out_stream; 17 17

Summary of File I/O Statements Connect each stream to a file using the open member function with external file name as argument. Always use the member function fail to test if the call succeeded. in_stream.open( infile.dat ); if (in_streamin.fail()); { cout<< Input file opening failed.\n ; exit(1); } out_stream.open( outfile.dat ); if(out_stream.fail()) { cout << Output file opening failed\n ; exit(1); } 18 18

Summary of File I/O Statements Use the stream in_stream to get input from the file infile.dat just like you use cin input from the keyboard. Example: in_stream >> some_variable >> another_variable; Use the stream out_stream to send output to the file outfile.dat just like you use cout output to the screen. Example: out_stream << some_variable = << some_variable << endl; Close the streams using the member function close: in_stream.close(); out_stream.close(): 19 19

Take a Break 20

Object notation for streams (our magic formula for decimal point output) out_stream.setf(ios::fixed); out_stream.setf(ios::showpoint); out_stream.precision(2); 21

member functions for output streams precision number of significant digits (or decimal places, depending on compiler) width how many (minimum) spaces in output (line up output) unsetf unset flags that are set with setf (see next slide) 22

set flags (Display 5.5 page 220) ios::fixed decimal point rather than exponential notation ios::scientific floating point numbers written in e-notation (opposite of fixed) ios::showpoint always include the decimal point even if there are no significant digits after the decimal point (2.0 rather than 2) ios::showpos write plus sign in front of positive numbers ios::right right justify value ios::left left justify value (opposite of ios::right) 23

Manipulators functions called in a non-traditional way setw same as width setprecision same as precision 24

Examples of manipulators out_stream << Start << setw(4) << 10 << setw(4) << 20 << setw(10) << 30; outputs: Start 10 20 30 25

Streams can be arguments to functions But must be call-by-reference void make_neat (ifstream& messy, ofstream& neat) 26

End-of-file read returns true if a value is read read returns false if no value is read (eof) while (messy_file >> next) //check for eof { cout << setw(field_width ) << next << endl; neat_file << setw(field_width ) << next << endl; } //(messy_file >> next) both action and Boolean expression 27

get and put input and output characters works sort of like insertion and extraction operators for type char without automatic skipping of blanks or understanding of escape sequences. takes everything in as a character. can detect end of line by checking value of character 28

Syntax for get and put input_stream.get(char_variable); output_stream.put(char_variable); 29

Example of get char var; do { cin.get(var); cout << var; } while (var!= \n ) // character variable // get a character // output the character // check for end of line 30

EOF member function returns true if end of file instream.get(next); while (! instream.eof() ) { cout << next; instream.get(next); } // check for eof 31

Predefined Character functions Pre-defined character functions: toupper converts to upper case tolower converts to lower case isupper returns true if character is uppercase islower returns true if character is lower case isalpha returns true if character is a letter (a z or A Z) isdigit returns true if character is a number (0 9) isspace returns true id character is a blank or newline 32

Quirks in Microsoft If you want to use the input file twice, you must first close it then open it a second time. If you don t re-open it, the second time you try to use it, it will be at the end of the file. However, in Microsoft, you won t be able to re-open the same stream. So use two stream variables in_stream and in_stream2 (or fin and fin2 or whatever). Don t forget to close the first stream before opening the second!!! 33

Namespace *Book s note on using directives just put it after the includes, but realize that when you want to use something other than namespace, you will have to make the using statements local to the functions. 34

Programming with I/O streams declare a stream: ifstream numbers_in; connect a stream to a file: numbers_in.open(a://data1.txt); verify that the file opened correctly: if numbers_in.fail(); { cout << Error message/n ; exit (1); } close the stream: numbers_in.close(); 35

Reading Assignment Arrays Sections 10.1-10.2 pages 493 524 36

Take a Break! 37