C++ Review Some things you’re supposed to know. Your Background n Should have CSC 226/227 or equivalent  selection commands: if, switch  repetition.

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
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.
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.
File streams Chapter , ,
1 CS 105 Lecture 8 Strings; Input Failure Mon, Mar 7, 2011, 3:39 pm.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
1 10/25/06CS150 Introduction to Computer Science 1 Reading from and Writing to Files.
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
Chapter 8 Streams and Files Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University Millersville, PA
In Addition... To the string class from the standard library accessed by #include C++ also has another library of string functions for C strings that can.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
File I/O ifstreams and ofstreams Sections 11.1 &
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 CS161 Introduction to Computer Science Topic #13.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
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.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
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.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
C++ Classes and Data Structures Jeffrey S. Childs
4. Input/Output Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 C++ Input/Output: Streams The.
Copyright © 2002, Department of Systems and Computer Engineering, Carleton University CONTROL STRUCTURES Simple If: if (boolean exp) { statements.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
1 Character Strings (Cstrings) Reference: CS215 textbook pages
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
Quiz // // The function exchanges the two parameters. // Param: ( ) // Param:
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Managers and “mentors” identified on projects page. All member accounts created and projects populated.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 9. Streams & Files.
11 Introduction to Object Oriented Programming (Continued) Cats.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
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.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
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.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.
Advanced File Operations Chapter File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to.
File I/O. Files allow permanent storage of programs and data. ifstream and ofstream objects –For file I/O the inclusion of is required. –Objects for file.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
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 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eight: Streams Slides by Evan Gallagher.
Copyright © 2003 Pearson Education, Inc.
Standard Input/Output Streams
Standard Input/Output Streams
File I/O with Records Lesson xx
Today’s Lecture I/O Streams Tools for File I/O
when need to keep permanently
CSC 143 Stream I/O Classes and Files [A11-A15, A38-A50]
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
Reading from and Writing to Files
Lecture 3 More on Flow Control, More on Functions,
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

C++ Review Some things you’re supposed to know

Your Background n Should have CSC 226/227 or equivalent  selection commands: if, switch  repetition commands: while, for, do-while  writing & using functions  arrays & structs (also typedef)  writing & using classes n Experience with a C++ IDE  Visual Studio.NET is what we’ll be using

Review Material n File I/O  End-of-file loop control n Reference parameters  passing streams to functions n C++ string variables n Structured types n Classes

Using Files n #include n #include  has required definitions n Each file requires a separate stream  just as cin and cout are streams n Each file stream either input or output  just like cin and cout n Each file stream is a variable

Streams vs. Files n Different things = different names  file name  stream name Input File Output File Program Input File Stream Output File Stream DATAIN.TXTDATAOUT.TXT fin fout MYPROG.EXE

Declaring File Streams n Input stream  ifstream fileVariable; n Output stream  ofstream fileVariable; n Creates streams—still need to “attach” a file  fileVariable.open(“fileName”);  fileVariable.close();when you’re done

File Open Errors n A file may not exist when we open it  output file OK – it will be created  input file problem – no file to attach to n May not have create privileges in a folder  output file can’t be created = error n Error = Stream enters fail state  and then ignores all commands on that stream

Checking for Fail State n Streams can be treated as booleans  stream is in a fail state = false  stream not in a fail state = true n After opening a file, ask if it’s false  false = fail state = error opening n inStream.open(“MayExist.TXT”); if (!inStream) …

Opening and Testing a File ifstream fin; fin.open(“SomeFile.TXT”); if (!fin) { cout << “Couldn’t open SomeFile.TXT\n” << “Exiting program.\n”; exit(1);}

EOF Controlled Loops n If we want to read all the data in a file… n …we just read until the stream fails while (inStream) … n Can’t read anything more from that stream  that’s OK – we wanted to read everything, and now we have  just inStream.close() and you’re done with it

Example: File Length int count = 0; char ch; infile.get(ch); while (infile) {count++;infile.get(ch);}infile.close(); Note:End-of-File controlled loop runs until file is done initialization (priming read) test (for input failure) processing update (read next)

Priming Read & Update n Can combine n Read returns stream n Test read command  failed read = false  OK read = true n Also OK:  while (infile >> n) int count = 0; char ch; while (infile.get(ch)) {count++;}infile.close();

Functions That Read n Can use a function to read into a variable n Need a reference parameter  passing a variable instead of a value n Value parameter  void DoThis(int n); n Reference parameter  void ReadThis(int& n);

Reference Parameter n AKA “pass-by-address” n Parameter address gets sent down  the variable itself, not just its value n Change parameter = change argument  parameter = in the called function  argument = in the calling function

Data Flow n Data goes into the function  Value parameters n Data comes out of the function  Reference parameters n Some parameters carry data both ways  Reference parameters

In-Out Parameters n Passes information in and out void Swap(int& first, int& second); int m = 10; int n = 5; cout << “m = ” << m << “, n = ” << n << endl; Swap(m, n); cout << “m = ” << m << “, n = ” << n << endl; m = 10, n = 5 m = 5, n = 10

Swap Function void Swap(int& first, int& second) { int temp = first; first = second; second = temp; }

Documenting Data Flow n /* in */, /* out */ and /* inout */ void ReadNumLines( /* out */ int& numLines ) void PrintLine( /* in */int numLines ) void DoThis(/* in */intstart, /* inout */int&finish, /* out */bool&errorFlag )

File Stream Parameters n Can pass file streams to functions  usually pass them after they’re opened/OK  usually don’t close them n Use reference parameters (pass-by-address)  the streams change when you use them void make_neat(ifstream& messy, ofstream& neat);

Neatening Files ifstream fin(“Messy.txt”); ofstream fout(“Neat.txt”); if (!fin || !fout) { cout << “Could not open files” << endl; exit(1);} make_neat(fin, fout); fin.close();fout.close();

Using File Stream Parameters n Used just like other file stream variables void make_neat(/* inout */ ifstream& messy, /* inout */ ofstream& neat) {neat.setf(ios::fixed);neat.setf(ios::showpoint);neat.precision(5); // … continued …

Using File Stream Parameters // … continued … double x; while (messy >> x) { neat << setw(10) << x << endl; }} Note:End-of-File controlled loop runs until file is done

Reading File Names n Above uses “hard-coded” file names n Would like to ask user for file name n Need a string variable  can use C strings or C++ strings  C++ strings easier to use…  …but.open() needs a C string  Can convert C++ string to C string

String Class n Need to include string library #include #include string str1; string str2(“This is a string”); n Can do assignment using = str1 = str2;// now str1 == “This is a string”

C Strings v. C++ Strings n C strings are character arrays  char* or char[] n Need special functions to assign, compare  strcpy(dst, src); if (strcmp(s1, s2) < 0) … n C++ strings are objects  can use usual operations on them  dst = src; if (s1 < s2) …  convert to C string using.c_str()

Sample With File Name Input string fileName; cout << “What file should I use?” << endl; cin >> fileName; cin.ignore(100, ‘\n’); ifstream fin(fileName.c_str()); // needs C string if (!fin) { cout << “Could not open ” << fileName; exit(1);}

String Parameters n Can also pass strings to functions  NOTICE: the string is the file name  IMPORTANT: the string is not the file  IMPORTANT: the string is not the stream n Pass by reference  saves copying the string itself n Mark as const if it’s not to be changed  to prevent accidental changes

Process a File Function void ProcessFile(/* in */ const string& fileName) { // create, open & test stream – close when done ifstream fin(fileName.c_str()); if (!fin) // exit or return as appropriate // file processing goes here fin.close();}

Input & Output on Strings n Just like for C-style strings cin >> str1; cout << “You entered ” << str1 << endl; n One word at a time for input  skips whitespace; reads non-whitespace; stops at whitespace; n Use getline if you want to read a line  reads to end of line & gets rid of ‘\n’ character

getline Function not a Member n Need to specify both input stream and string getline(cin, str1); n Input stream can be either cin or file stream getline(inFile, str1); n Optional third argument is terminator getline(cin, str1, ‘.’);  default terminator is ‘\n’

getline Problems n Visual C++ 6 had trouble with getline(cin, …)  needs one character after the ‘\n’  doesn’t do anything with it, but it must be there  sometimes get weird behaviour (won’t prompt for next file until press ENTER twice, e.g.) n Works fine with files, and has been fixed in Visual Studio.NET

Records (C++ Structs) n For “lumping” information together struct Student { long stuNum; long stuNum; int pctGrade; int pctGrade; char letterGrade; char letterGrade; string name; string name;}; A type for Students NOT a variable

Record Variables n Once declared, it’s just another data type  can declare variables of that type  including array variables Student joe; Student sally; Student classList[100]; An array of 100 Students

Student Record n “Bundle” of information about a student A Addams, Wednesday A Cardew, Cecily D Bravo, Johnny Student Number Percent Grade Letter Grade Name

Note on Component Types n They don’t have to be different n They just don’t have to be the same struct Date { int year; int month; int month; int day; }; int day; }; struct Customer { long number; char name[31]; char name[31]; double balance; }; double balance; };

Initializing a Record Variable n Values can be set at declaration: Student stu = { , 76, 76, ‘B’, ‘B’, “Wooster, Bertie” }; “Wooster, Bertie” }; Date births[] = {{ 1974, 10, 4}, { 1977, 1, 23}, { 1977, 1, 23}, { 1979, 2, 6}, { 1979, 2, 6}, { 1981, 8, 4}}; { 1981, 8, 4}};

Picking Out The Components n To talk about them  varName.fieldName  arrName[i].fieldName n Examples: cout << someStu.stuNum; cout << someStu.stuNum; cout << stuList[4].name; cout << stuList[4].name; n General syntax: structName.fieldName

Pointed-at Components n When you have a pointer to a struct…  Student* stu; n …need to either use parentheses…  (*stu).name n …or arrow  stu->name

Prototypes & Headings n A “best practice” is to always pass structs by reference  and use CONST for “in” parameters void DoStuff(const Student& s); void DoMore(Student& s);

Example Function void ReadStudent( /* out */ Student& s ) { cout >> “Enter student number: ”; cout >> “Enter student number: ”; cin >> s.stuNum; cin.ignore(10, ’\n’); cin >> s.stuNum; cin.ignore(10, ’\n’); cout << endl << “Student’s name: ”; cout << endl << “Student’s name: ”; cin.get(s.name, 40); cin.ignore(10, ’\n’); cin.get(s.name, 40); cin.ignore(10, ’\n’); cout << endl << “Student’s grade: ”; cout << endl << “Student’s grade: ”; cin >> s.pctGrade; cin.ignore(10, ’\n’); cin >> s.pctGrade; cin.ignore(10, ’\n’); cout << endl; cout << endl; s.letterGrade = PctToLetter(s.pctGrade); s.letterGrade = PctToLetter(s.pctGrade);}

Structures & Functions n Many functions will use the structures n Some function are basic to the structure  reading a value  printing a value  changing a field n These should be “bundled” with the fields n Use class instead of struct for that

Structs to Classes n Classes very much like structs class CIntList100 { private: private: int data[100]; int data[100]; int length; int length;}; CIntList100 list; class instead of struct keyword private: more differences later

Member Functions n Also go in the class definition n One per operation allowed n Access specifier is “public:”... n...so that other functions can use them

Class with Member Functions class CIntList100 { public: void Read(); void AddItem(int); void AddItem(int); void RemoveItem(int); void RemoveItem(int); void Write(); void Write(); bool Contains(int); bool Contains(int); bool IsEmpty(); bool IsEmpty(); int Length(); int Length(); private: int data[100]; private: int data[100]; int length; int length;}

“Missing” Parameter n Member functions belong to objects class CIntList100 { public: void Read(); …}; CIntList100 list; n list object has Read function as a member  calling that Read will Read that list  list.Read();

Calling Member Functions n Use component selection to get function  CIntList100 list;  list.AddItem(10); n For pointed-at objects, use arrow  CIntList100* listPtr;  …  listPtr->AddItem(10);

Operation Types class CIntList100 { public: void Read(); // transformer void Read(); // transformer void AddItem(int); // transformer void AddItem(int); // transformer void RemoveItem(int); // transformer void RemoveItem(int); // transformer void Write(); // observer void Write(); // observer bool Contains(int); // observer bool Contains(int); // observer bool IsEmpty(); // observer bool IsEmpty(); // observer int Length(); // observer int Length(); // observer......

Operation Types and Parameters n Transformer functions correspond to out or inout parameters void Read(IntList100&); => void Read(); // transformer n Observer functions correspond to in parameters void Contains(const IntList100&, int); => void Contains( int ); // observer

Marking Observer Operations class CIntList100 { public: // transformers // transformers void Read(); void Read(); // observers // observers void Write() const; void Write() const; bool Contains(int) const; bool Contains(int) const; bool IsEmpty() const; bool IsEmpty() const; int Length() const; int Length() const;......} const reserved word – prevents changes to object – documents function as an observer

Constructors & Destructors n Classes also have constructors  function that gets called when object is created  initializes the fields n and destructors  function called when objects are destroyed  makes sure no memory leak

Constructors & Destructors class CIntList100 { public: // constructors // constructors CIntList100(); CIntList100(); CIntList100(int initialElement); CIntList100(int initialElement); // destructor // destructor ~CIntList100(); ~CIntList100();......}

Using Classes n Classes are usually split into two parts n Declaration = Interface  says what it is & what it can do n Definition = Implementation  says how it does it n Client doesn’t need to see the latter but does need to see the former

Sample Classes n Menu  text-based menu class  for console programs n TextItems  for outputting large text blocks  initialized from a file  parts of file output as required