No I/O is built into C++ l instead, a library provides input stream and output stream KeyboardScreen executing program istreamostream 1.

Slides:



Advertisements
Similar presentations
C++ Plus Data Structures
Advertisements

This set of slides is provided by the author of the textbook1 Introductory Topics (Continued) l Computer Components l Basic Control Structures l Problem.
1 Chapter 6 Object-Oriented Software Design and Implementation.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Important Definitions Class: A structured data type that is used to represent an abstract data type (ADT) Class member: A components of a class. It can.
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
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.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
1 Programming Style Files Lecture 1 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Modified by Reneta Barneva, SUNY-Fredonia.
1 Chapter 1 Overview of Programming and Problem Solving Dale/Weems/Headington Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Program Input and the Software Design Process ROBERT REAVES.
1 Author: Nell Dale Chip Weems Mark Headington Published By Higher Education Press Jones and Bartlett Publishers.
C++ Vs. Java Who will win?. Look Ma, no classes! C++ was conceived as an object-oriented extension to C C was (is) purely procedural language –Functions.
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.
1 Chapter-01 Programming Methodologies Procedural/Structured Design Objected-Oriented Design.
1 Chapter 4 Program Input and the Software Design Process.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
1 Chapter 4 Program Input and the Software Design Process CS185/09 - Introduction to Programming Caldwell College.
Overview of Programming and Problem Solving Textbook Chapter 1 1.
Chapter 1 Software Engineering Principles. Lecture 2.
File I/O ifstreams and ofstreams Sections 11.1 &
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.
1 Chapter 1 Overview of Programming and Problem Solving Dale/Weems/Headington.
Programming Life Cycle Problem analysisunderstand the problem Requirements definition specify what program will do High- and low-level designhow it meets.
Introduction to C++ Version 1.1. Topics C++ Structure Primitive Data Types I/O Casting Strings Control Flow.
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.
Input/Output Sujana Jyothi C++ Workshop Day 2. C++ I/O Basics 2 I/O - Input/Output is one of the first aspects of programming that needs to be mastered:
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
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.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
1 Program Input Software Design Chapter 4. 2 You Will Want to Know... Prompting for and reading values into a program. Accessing data from a file. What.
1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.
Chapter 1 Overview of Programming and Problem Solving CS185/09 - Introduction to Programming Caldwell College.
1 Program Input and the Software Design Process. 2 Chapter 4 Topics  Input Statements to Read Values for a Program using >>, and functions get, ignore,
Chapter 4 Program Input and the Software Design Process.
1 What is a Named Constant? A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed.
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.
More about strings in C++. String member functions The next three slides present information about functions that are members of the C++ string class.
Program Input and the Software Design Process ROBERT REAVES.
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.
1 Chapter 4 Program Input and the Software Design Process.
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.
CS221 C++ Basics. C++ Data Types structured array struct union class address pointer reference simple integral char short int long bool floating float.
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.
Chapter 4 Program Input and the Software Design Process
Chapter 1 Software Engineering Principles
Input and Output Chapter 3.
File I/O.
Lecture 5A File processing Richard Gesick.
Chapter 3: Input/Output
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.
Chapter 4 Program Input and the Software Design Process
Formatted Input, Output & File Input, Output
CHAPTER 4 File Processing.
Dale/Weems/Headington Program Input and the Software Design Process
File I/O in C++ I.
Presentation transcript:

No I/O is built into C++ l instead, a library provides input stream and output stream KeyboardScreen executing program istreamostream 1

SYNTAX These examples yield the same result. cin >> length ; cin >> width ; cin >> length >> width ; Input Statements cin >> Variable >> Variable... ; 2

Whitespace Characters Include... l blanks l tabs l end-of-line (newline) characters The newline character is created by hitting Enter or Return at the keyboard, or by using the manipulator endl or “\n” in a program. 3

At keyboard you type: [ space ] 25 [ space ] J [ space]2 [ Enter ] int age ; char initial ; float bill ; cin >> age ; cin >> initial ; cin >> bill ; NOTE: A file reading marker is left pointing to the newline character after the 2 in the input stream. ageinitialbill ageinitialbill 25‘J’2.0 4

Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) KeyboardScreen executing program input data output data 5

6 The get( ) function can be used to read a single character. It obtains the very next character from the input stream without skipping any leading whitespace characters. Another Way to Read char Data

char first ; char middle ; char last ; cin.get ( first ) ; cin.get ( middle ) ; cin.get ( last ) ; NOTE: The file reading marker is left pointing to the space after the ‘B’ in the input stream. firstmiddlelast At keyboard you type: A [ space]B [ space ] C [ Enter] firstmiddlelast ‘A’‘ ’‘B’ 7

8 Use function ignore( ) to skip characters The ignore( ) function is used to skip (read and discard) characters in the input stream. The call cin.ignore ( howMany, whatChar ) ; will skip over up to howMany characters or until whatChar has been read, whichever comes first.

An Example Using cin.ignore( ) abc abc abc abc NOTE: shows the location of the file reading marker STATEMENTS CONTENTS MARKER POSITION int a ; \n int b ; \n int c ; cin >> a >> b ; \n \n cin.ignore(100, ‘\n’) ; \n \n cin >> c ; \n \n 9

Another Example Using cin.ignore( ) ich ich i i 16‘A’ NOTE: shows the location of the file reading marker STATEMENTS CONTENTS MARKER POSITION int i ; A 22 B 16 C 19\n char ch ; cin >> ch ; A 22 B 16 C 19\n cin.ignore(100, ‘B’) ; A 22 B 16 C 19\n cin >> i ; A 22 B 16 C 19\n 10

11 EXAMPLE string message ; cin >> message ; cout << message ; HOWEVER... String Input in C++ Input of a string is possible using the extraction operator >>.

12 String Input Using >> string firstName ; string lastName ; cin >> firstName >> lastName ; Suppose input stream looks like this: Joe Hernandez 23 WHAT ARE THE STRING VALUES?

13 Results Using >> string firstName ; string lastName ; cin >> firstName >> lastName ; RESULT “J o e” “Hernandez” firstName lastName

Diskette Files for I/O your variable (of type ifstream) your variable (of type ofstream) disk file “A:\myInfile.dat” disk file “A:\myOut.dat” executing program input dataoutput data #include 14

To Use Disk I/O, you must l use #include l choose valid identifiers for your filestreams and declare them l open the files and associate them with disk names l use your filestream identifiers in your I/O statements (using >> and <<, manipulators, get, ignore) l close the files 15

Statements for Using Disk I/O #include ifstream myInfile; // declarations ofstream myOutfile; myInfile.open(“A:\\myIn.dat”);// open files myOutfile.open(“A:\\myOut.dat”); myInfile.close( );// close files myOutfile.close( ); 16

What does opening a file do? l associates the C++ identifier for your file with the physical (disk) name for the file l if the input file does not exist on disk, open is not successful l if the output file does not exist on disk, a new file with that name is created l if the output file already exists, it is erased l places a file reading marker at the very beginning of the file, pointing to the first character in it 17

Stream Fail State l when a stream enters the fail state, further I/O operations using that stream have no effect at all. But the computer does not automatically halt the program or give any error message l possible reasons for entering fail state include: invalid input data (often the wrong type) opening an input file that doesn’t exist opening an output file on a diskette that is already full or is write-protected 18

Entering File Name at Run Time #include // contains conversion function c_str ifstream inFile; string fileName; cout << “Enter input file name : “ << endl ; // prompt cin >> fileName ; // convert string fileName to a C string type inFile.open( fileName.c_str( ) ); 19

Functional Decomposition FOCUS is on actions and algorithms. BEGINS by breaking the solution into a series of major steps. This process continues until each subproblem cannot be divided further or has an obvious solution. UNITS are modules representing algorithms. A module is a collection of concrete and abstract steps that solves a subproblem. A module structure chart (hierarchical solution tree) is often created. DATA plays a secondary role in support of actions to be performed. 20

Compute Mileages Write Total Miles Module Structure Chart Main Get Data Round To Nearest Tenth Initialize Total Miles Open Files 21

Object-Oriented Design A technique for developing a program in which the solution is expressed in terms of objects -- self- contained entities composed of data and operations on that data. Private data << setf Private data >> get ignore cincout setw 22

More about OOD l languages supporting OOD include: C++, Java, Smalltalk, Eiffel, CLOS, and Object-Pascal l a class is a programmer-defined data type and objects are variables of that type l in C++, cin is an object of a data type (class) named istream, and cout is an object of a class ostream. Header files iostream and fstream contain definitions of stream classes l a class generally contains private data and public operations (called member functions) 23

Object-Oriented Design (OOD) FOCUS is on entities called objects and operations on those objects, all bundled together. BEGINS by identifying the major objects in the problem, and choosing appropriate operations on those objects. UNITS are objects. Programs are collections of objects that communicate with each other. DATA plays a leading role. Algorithms are used to implement operations on the objects and to enable interaction of objects with each other. 24

25 Two Programming Methodologies Functional Object-Oriented Decomposition Design FUNCTION OBJECT Operations Data OBJECT Operations Data OBJECT Operations Data

26 What is an object? OBJECT Operations Data set of functions internal state

27 An object contains data and operations Private data: accoutNumber balance OpenAccount WriteCheck MakeDeposit IsOverdrawn GetBalance checkingAccount

Why use OOD with large software projects? l objects within a program often model real-life objects in the problem to be solved l many libraries of pre-written classes and objects are available as-is for re-use in various programs l the OOD concept of inheritance allows the customization of an existing class to meet particular needs without having to inspect and modify the source code for that class--this can reduce the time and effort needed to design, implement, and maintain large systems 28

29 Company Payroll Case Study A small company needs an interactive program to figure its weekly payroll. The payroll clerk will input data for each employee. Each employee’s wages and data should be saved in a secondary file. Display the total wages for the week on the screen.

30 Algorithm for Company Payroll Program l Initialize total company payroll to 0.0 l Repeat this process for each employee 1. Get the employee’s ID empNum 2. Get the employee’s hourly payRate 3. Get the hours worked this week 4. Calculate this week’s wages 5. Add wages to total company payroll 6. Write empNum, payRate, hours, wages to file Write total company payroll on screen.

31 // *************************************************** // Payroll program // This program computes each employee’s wages and // the total company payroll // *************************************************** #include // for keyboard/screen I/O #include // for file I/O using namespace std; void CalcPay ( float, float, float& ) ; const float MAX_HOURS = 40.0; // Maximum normal hours const float OVERTIME = 1.5; // Overtime pay factor Company Payroll Program

32 C++ Code Continued int main( ) { float payRate; // Employee’s pay rate float hours;// Hours worked float wages; // Wages earned float total;// Total company payroll int empNum;// Employee ID number ofstream payFile;// Company payroll file payFile.open( “payfile.dat” );// Open file total = 0.0;// Initialize total

33 cout << “Enter employee number: “; // Prompt cin >> empNum; // Read ID number while ( empNum != 0 ) // While not done { cout << “Enter pay rate: “; cin >> payRate ; // Read pay rate cout << “Enter hours worked: “; cin >> hours ; // and hours worked CalcPay(payRate, hours, wages); // Compute wages total = total + wages; // Add to total payFile << empNum << payRate << hours << wages << endl; cout << “Enter employee number: “; cin >> empNum; // Read ID number }

34 cout << “Total payroll is “ << total << endl; return 0 ;// Successful completion } // *************************************************** void CalcPay ( /* in */ float payRate, /* in */ float hours, /* out */ float& wages ) // CalcPay computes wages from the employee’s pay rate // and the hours worked, taking overtime into account { if ( hours > MAX_HOURS ) wages = (MAX_HOURS * payRate ) + (hours - MAX_HOURS) * payRate * OVER_TIME; else wages = hours * payRate; } 34