Download presentation
Presentation is loading. Please wait.
Published bySandra Wright Modified over 8 years ago
1
C++ Review Some things you’re supposed to know
2
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
3
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
4
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
5
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
6
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
7
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
8
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) …
9
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);}
10
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
11
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)
12
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();
13
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);
14
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
15
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
16
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
17
Swap Function void Swap(int& first, int& second) { int temp = first; first = second; second = temp; }
18
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 )
19
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);
20
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();
21
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 …
22
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
23
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
24
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”
25
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()
26
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);}
27
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
28
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();}
29
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
30
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’
31
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
32
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
33
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
34
Student Record n “Bundle” of information about a student 9799999 95 A Addams, Wednesday 9822222 92 A Cardew, Cecily 9811111 53 D Bravo, Johnny Student Number Percent Grade Letter Grade Name
35
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; };
36
Initializing a Record Variable n Values can be set at declaration: Student stu = { 2877665, 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}};
37
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
38
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
39
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);
40
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);}
41
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
42
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
43
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
44
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;}
45
“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();
46
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);
47
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......
48
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
49
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
50
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
51
Constructors & Destructors class CIntList100 { public: // constructors // constructors CIntList100(); CIntList100(); CIntList100(int initialElement); CIntList100(int initialElement); // destructor // destructor ~CIntList100(); ~CIntList100();......}
52
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
53
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.