Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington.

Similar presentations


Presentation on theme: "1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington."— Presentation transcript:

1

2 1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington

3 2 Chapter 4 Topics Input Statements to Read Values for a Program using >>, and functions get, ignore, getline l Prompting for Interactive Input/Output l Using Data Files for Input and Output l Object-Oriented Design Principles l Functional Decomposition Methodology

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

5 is header file l for a library that defines 3 objects an istream object named cin (keyboard) an ostream object named cout (screen) an ostream object named cerr (screen)

6 5 Giving a Value to a Variable In your program you can assign (give) a value to the variable by using the assignment operator = ageOfDog = 12; or by another method, such as cout << “How old is your dog?”; cin >> ageOfDog; NOTE the prompt.

7 >> is a binary operator >> is called the input or extraction operator >> is left associative EXPRESSIONHAS VALUE cin >> age cin STATEMENT cin >> age >> weight ;

8 Extraction Operator ( >> ) l variable cin is predefined to denote an input stream from the standard input device ( the keyboard ) l the extraction operator >> called “get from” takes 2 operands. The left operand is a stream expression, such as cin--the right operand is a variable of simple type. l operator >> attempts to extract the next item from the input stream and store its value in the right operand variable

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

10 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.

11 Extraction Operator >> “skips over” (actually reads but does not store anywhere) leading white space characters as it reads your data from the input stream (either keyboard or disk file)

12 char first ; char middle ; char last ; cin >> first ; cin >> middle ; cin >> last ; NOTE: A file reading marker is left pointing to the newline character after the ‘C’ in the input stream. firstmiddlelast At keyboard you type: A [ space]B [ space ] C [ Enter] firstmiddlelast ‘A’‘B’‘C’

13 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

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

15 STATEMENTS CONTENTS MARKER POSITION int i ; 25 A\n char ch ; 16.9\n float x ; cin >> i ; 25 A\n 16.9\n cin >> ch ; 25 A\n 16.9\n cin >> x ; 25 A\n 16.9\n Another example using >> ichx 25 ‘A’ ichx i x i x 16.925‘A’ NOTE: shows the location of the file reading marker

16 Extraction Examples cin >> i; 32i = 32 cin >> i >> j; 4 60i = 4, j = 60 cin >> i >> ch >> x; 25 A 16.9i = 25, ch = ‘A’, x = 16.9 cin >> i >> ch >> x; 25 A 16.9i = 25, ch = ‘A’, x = 16.9 cin >> i >> ch >> x; 25A16.9i = 25, ch = ‘A’, x = 16.9 cin >> i >> j >> x; 12 8i = 12, j = 8 Computer waits cin >> i >> x; 46 32.4 15i = 46, x = 32.415 held

17 16 What is the error? l float rate; l float time; l float distance = rate * time; l cin >> rate >> time;

18 17 get( ), ignore( ), & getline( ) Functions

19 18 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

20 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’

21 Extraction Examples cin >> ch1; A B\nch1 = ‘A’ cin >> ch2; CD\n ch2 = ‘B’ cin >> ch3; ch3 = ‘C’; read marker on D cin.get(ch1); A B\nch1 = ‘A’ cin.get(ch2); CD\n ch2 = ‘ ’ cin.get(ch3); ch3 = ‘B’; read marker on \n cin >> ch1; A B\nch1 = ‘A’ cin >> ch2; CD\n ch2 = ‘B’ cin.get(ch3); ch3 = ‘\n’; read marker on C

22 21 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.

23 An Example Using cin.ignore( ) abc abc abc abc 95734 95734128 95734 NOTE: shows the location of the file reading marker STATEMENTS CONTENTS MARKER POSITION int a ; 957 34 1235\n int b ; 128 96\n int c ; cin >> a >> b ; 957 34 1235\n 128 96\n cin.ignore(100, ‘\n’) ; 957 34 1235\n 128 96\n cin >> c ; 957 34 1235\n 128 96\n

24 Another Example Using cin.ignore( ) ich 95734 95734 95734 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

25 Extraction Examples cin >> i >> j;957 34 1235\ni = 957 cin.ignore(100, ‘\n’);128 96\nj = 34 cin >> k; k = 128 read mark ‘ ‘ cin >> ch;A 22 B 16 C 19\nch = ‘A’ cin.ignore(100, ‘B’); cin >> i; i = 16 read mark ‘ ‘ cin.ignore(2, ‘\n’);ABCDEF\n cin >> ch; ch = ‘C’ read mark ‘D‘

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

27 26 Extraction operator >> When using the extraction operator ( >> ) to read input characters into a string variable: l the >> operator skips any leading whitespace characters such as blanks and newlines l it then reads successive characters into the string, and stops at the first trailing whitespace character (which is not consumed, but remains waiting in the input stream)

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

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

30 29 getline( ) Function l Because the extraction operator stops reading at the first trailing whitespace, >> cannot be used to input a string with blanks in it l use getline function with 2 arguments to overcome this obstacle l First argument is an input stream variable, and second argument is a string variable EXAMPLE string message ; getline (cin, message ) ;

31 30 getline(inFileStream, strg) l getline does not skip leading whitespace characters such as blanks and newlines l getline reads successive characters (including blanks) into the string, and stops when it reaches the newline character ‘\n’ l the newline is consumed by get, but is not stored into the string variable

32 31 String Input Using getline string firstName ; string lastName ; getline (cin, firstName ); getline (cin, lastName ); Suppose input stream looks like this: Joe Hernandez 23 WHAT ARE THE STRING VALUES?

33 32 Results Using getline “ Joe Hernandez 23” ? firstName lastName string firstName ; string lastName ; getline (cin, firstName ); getline (cin, lastName );

34 Interactive I/O l in an interactive program the user enters information while the program is executing l before the user enters data, a prompt should be provided to explain what type of information should be entered l after the user enters data, the value of the data should be printed out for verification. This is called echo printing l that way, the user will have the opportunity to check for erroneous data

35 Prompting for Interactive I/O cout << “Enter part number : “ << endl ; // prompt cin >> partNumber ; cout << “Enter quantity ordered : “ << endl ; cin >> quantity ; cout << “Enter unit price : “ << endl ; cin >> unitPrice ; totalPrice = quantity * unitPrice ; // calculate cout << “Part # “ << partNumber << endl ; // echo cout << “Quantity: “ << quantity << endl ; cout << “Unit Cost: $ “ << setprecision(2) << unitPrice << endl ; cout << “Total Cost: $ “ << totalPrice << endl ;

36 35 File I/O

37 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

38 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

39 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( );

40 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

41 Accessing files in C++ 1. Insert #include 2. Declare the files we are going to use. 3. open each file 4. Specify name of file in each input or output.

42 Example of declaring & opening file streams ifstream inMPG;// an input file ofstream outMPG;// an output file inMPG.open(“S:\\cp1\\inmpg.dat”); outMPG.open(“R:\\outmpg.dat”); // OR combining ifstream inMPG(“S:\\cp1\\inmpg.dat”);

43 Specifying file name on I/O inMPG >> amt1 >> amt2 >> startMiles; outMPG << “miles per gallon = “ << mpg; l See Program n S:\cp1\cpp\mileage2.cpp

44 Input Failure l When reading into an integer variable n What if you enter letters? l Input operation fails cin enters a fail state n further I/O on the stream have no effect n computer will NOT give an error message

45 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

46 Fail State l int i=10, j=20, k=30; l cin >> i >> j >> k; l Suppose the following input: l 1234.56 7 89 l cout << “i: “ << i << “ j: “ << j << “ k: “ << k; l The resulting output: l i: 1234 j: 20 k: 30 l Inability to open an input file results in fail state

47 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( ) );

48 Functional Decomposition A technique for developing a program in which the problem is divided into more easily handled subproblems, the solutions of which create a solution to the overall problem. In functional decomposition, we work from the abstract (a list of the major steps in our solution) to the particular (algorithmic steps that can be translated directly into code in C++ or another language).

49 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.

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

51 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

52 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)

53 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.

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

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

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

57 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

58 57 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.

59 58 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.

60 59 // *************************************************** // 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

61 60 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

62 61 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 }

63 62 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; }

64 63


Download ppt "1 Chapter 4 Program Input and the Software Design Process Dale/Weems/Headington."

Similar presentations


Ads by Google