CS 144 Advanced C++ Programming February 5 Class Meeting

Slides:



Advertisements
Similar presentations
Chapter 12 Streams and File I/O Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
Advertisements

Chapter 12 Streams and File I/O. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  I/O Streams  File I/O  Character.
I/O Streams as an Introduction to Objects and Classes
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
C++ Programming: From Problem Analysis to Program Design, Fifth 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.
Chapter 3: Input/Output
CSCE 121: Introduction to Program Design and Concepts J. Michael Moore Fall 2014 Set 11: More Input and Output 1 Based on slides created by Bjarne.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
STREAMS AND FILES OVERVIEW.  Many programs are "data processing" applications  Read the input data  Perform sequence of operations on this data  Write.
Chapter 12 Streams and File I/O. Learning Objectives I/O Streams – File I/O – Character I/O Tools for Stream I/O – File names as input – Formatting output,
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 3: Input/Output.
File I/O ifstreams and ofstreams Sections 11.1 &
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 3 Formatting Output.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
I/O and Data Formatting Introduction to Class Concepts INFSY 307 Spring 2003 Lecture 3.
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.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 6 I/O Streams as an Introduction to Objects and Classes.
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: Input/Output. Objectives In this chapter, you will: – Learn what a stream is and examine input and output streams – Explore how to read data.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
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.
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.
Copyright © 2002 Pearson Education, Inc. Slide 1.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.
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.
CMPE Data Structures and Algorithms in C++ September 9 Class Meeting Department of Computer Engineering San Jose State University Fall 2016 Instructor:
I/O Streams as an Introduction to Objects and Classes
Introduction to C++ (Extensions to C)
C++ Basic Input and Output (I/O)
ifstreams and ofstreams
CMPE Data Structures and Algorithms in C++ September 7 Class Meeting
Auburn University COMP 3000 Object-Oriented Programming for Engineers and Scientists File I/O Dr. Xiao Qin Auburn University.
EGR 2261 Unit 3 Input/Output Read Malik, Chapter 3.
I/O Streams as an Introduction to Objects and Classes
COMP 2710 Software Construction File I/O
Copyright © 2003 Pearson Education, Inc.
CMPE 180A Data Structures and Algorithms in C++ February 15 Class Meeting Department of Computer Engineering San Jose State University Spring 2018 Instructor:
Chapter 2 part #3 C++ Input / Output
CMPE 180A Data Structures and Algorithms in C++ February 1 Class Meeting Department of Computer Engineering San Jose State University Spring 2018 Instructor:
Standard Input/Output Streams
Standard Input/Output Streams
Input/Output Handouts: Quiz 2, Unit 3 practice sheets.
Chapter 6 I/O Streams as an Introduction to Objects and Classes 1.
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
Chapter 5 Input and Output Streams
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Review of Strings which include file needs to be used for string manipulation? what using statement needs to be included for string manipulation? how is.
Chapter 3: Input/Output
Chapter 3 Input output.
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
Chapter 3: Expressions and Interactivity
Formatted Input, Output & File Input, Output
CS 144 Advanced C++ Programming February 7 Class Meeting
CS 144 Advanced C++ Programming February 12 Class Meeting
Chapter 2 part #3 C++ Input / Output
CS 144 Advanced C++ Programming January 29 Class Meeting
CS 144 Advanced C++ Programming January 31 Class Meeting
Instructor: Dr. Michael Geiger Spring 2019 Lecture 13: Exam 1 Preview
ifstreams and ofstreams
Instructor: Dr. Michael Geiger Spring 2017 Lecture 12: Exam 1 Preview
Lecture 3 More on Flow Control, More on Functions,
File I/O in C++ I.
Presentation transcript:

CS 144 Advanced C++ Programming February 5 Class Meeting Department of Computer Engineering San Jose State University Spring 2019 Instructor: Ron Mak www.cs.sjsu.edu/~mak

Assignment #1: Sample Solution Do not attempt to write an entire program all at once and then try to get it to work. Develop the program iteratively. Each iteration incrementally adds functionality. Each iteration ends with working code. Always build on top of working code.

Assignment #1: Sample Solution, cont’d Suggested iterations: Read and print the input values (the numbers of plants). Use placeholders for the near and far plans. With a fixed number of plants (the input contains only 5 and 0), make one trip of the near plan. Add an inner loop to iteration 2 to make multiple trips until all the plants are watered. Test with different numbers of plants. Add the code for the far plan and the code to determine which plan is better.

Overloading Function Names A function is characterized by both its name and its parameters. Number and data types of the formal parameters. You can overload a function name by defining another function with the same name but with different parameters. The parameters must differ by number or data type. When you call a function with the shared name, the arguments of the call determine which function you mean.

Overloading Function Names, cont’d Example declarations: Example calls: Be careful with automatic type conversions of arguments when overloading function names. double average(double n1, double n2); double average(double n1, double n2, double n3); double avg2 = average(x, y); double avg3 = average(x, y, z);

Call-by-Value By default, arguments to a function are passed by value. A copy of the argument’s value is passed to the function. Any changes that the function makes to its parameters do not affect the calling arguments. Example: The faulty swap function.

Call-by-Value, cont’d void swap_by_value(int a, int b) { int temp = a; a = b; b = temp; } swaps.cpp Why doesn’t this function do what the programmer intended?

Call-by-Reference If you want the function to be able to change the value of the caller’s arguments, you must use call-by-reference. The address of the actual argument is passed to the function. Example: The proper exchange function.

Call-by-Reference, cont’d void swap_by_reference(int& a, int& b) { int temp = a; a = b; b = temp; } swaps.cpp Why is this code better? Demo

Procedural Abstraction Design your function such that the caller does not need to know how you implemented it. The function is a “black box”.

Procedural Abstraction, cont’d The function’s name, its formal parameters, and your comments should be sufficient for the caller. Preconditions: What must be true when the function is called. Postconditions: What will be true after the function completes its execution.

Testing and Debugging Functions There are various techniques to test and debug functions. You can add temporary cout statements in your functions to print the values of local variables to help you determine what the function is doing. With the Eclipse or the NetBeans IDE, you can set breakpoints, watch variables, etc.

assert Use the assert macro during development to check that a function’s preconditions hold. You must first #include <cassert> Example: Later, when you are sure that your program is debugged and you are going into production, you can logically remove all the asserts by defining NDEBUG before the include: assert(y != 0); quotient = x/y; #define NDEBUG #include <cassert>

assert, cont’d assert.cpp Demo #include <iostream> //#define NDEBUG #include <cassert> using namespace std; /** * Print a positive value. * @param n the value which must be > 0. */ void print_positive(int n); int main() { print_positive(-3); return 0; } void print_positive(int n) assert(n > 0); cout << "n = " << n << endl; assert.cpp Demo

Assignment #2: Monty Hall Problem Behind one door is a new car. Behind the other two doors are goats. Can you pick the right door?

Assignment #2: Monty Hall Problem, cont’d Do a hierarchical decomposition. Iteratively add new functionality to code that works. Choose good function names. Use parameters wisely. You will need to generate random numbers. Use the same seed value if you always want the same sequence of random numbers for testing. Your final program should have correct output and be easy to read.

Streams I/O (input/output) for a program can be considered a stream of characters. Represented in a program by a stream variable. An input stream into your program can be characters typed at the keyboard characters read from a file An output stream from your program can be characters displayed on the screen characters written to a file

File I/O In order for a program to read from a data file, it must first connect a stream variable to the file. #include <fstream> using namespace std; ... ifstream in_stream; // input file stream variable ofstream out_stream; // output file stream variable in_stream.open("infile.dat"); // connect to the input file out_stream.open("outfile.dat"); // connect to the output file // Read three integer values from the input file. int value1, value2, value3; in_stream >> value1 >> value2 >> value3; // Write to the output file. out_stream << "Value #1 is " << value1 << " and Value #2 is " << value2 << endl;

File I/O, cont’d Close a stream when you’re done with reading or writing it. Closing a stream releases the associated file for use by another program. in_stream.close(); out_stream.close();

Stream Name vs. File Name Do not confuse the name of a program’s stream variable with the name of the file. The stream variable’s name is internal to the program. The file’s name is external to the program. Calling a stream’s open method connects the stream to the file. A stream is an object. open and close are functions we can call on the object. We’ll learn about C++ classes and objects later.

cin and cout Predefined stream variables cin and cout represent standard in (keyboard) and standard out (monitor screen). You must have: When you run your program on the command line, you can use I/O redirection to redirect standard in and standard out to text files. #include <iostream> using namespace std;

Formatting Output Formatting a value that is being output includes Determine the width of the output field Decide whether to write numbers in fixed-point notation or in scientific notation Specify how many digits after the decimal point To format output to cout, call its member functions: Use fixed-point notation instead of scientific notation. Always include the decimal point in the output. Two digits after the decimal point. cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2);

Output Manipulators Manipulator function setw sets the width of an output field. Manipulator function setprecision sets the number of places after the decimal point. Embed calls to manipulators in output statements. Examples: #include <iomanip> using namespace std; ... cout << "Value 1 = " << setw(10) << value1 << end; cout << "$" << setprecision(2) << amount << endl;

Passing Streams to Functions Pass stream objects to functions only via call-by-reference. Example: Why? void copyFile(ifstream& source, ofstream& destination);

Character I/O Recall that the operator >> used on cin skips blanks. To read all characters from an input stream, including blanks, use the get method: Use the put method to output any character to an output stream: cout.put(ch); char ch; ... cin.get(ch);

Character I/O, cont’d You can use built-in function getline to read an entire input line, including blanks, into a string variable: string text; getline(cin, text);

Predefined Character Functions Some very useful Boolean functions that test a character: isupper(ch) islower(ch) isalpha(ch) isdigit(ch) isspace(ch) toupper(ch) tolower(ch)

The eof Function Boolean function eof tests whether or not an input stream has read the entire file. eof = end of file Example: Function eof returns true only after an attempt was made to read past the end of file. It’s not a warning that you’re about to read past the end of file. if (in_stream.eof()) ...