Download presentation
Presentation is loading. Please wait.
1
Organizing Your Program Code (P.508)
Ex8_11: Distribute the code among several files. (P.506) This make it easy for you if you want to re-use any code from existing files in a new project. .h - class definition data members function prototypes .cpp - class implementation
2
HW: Define a Class for the SpreadSheet
We are designing a spreadsheet program. Users can input numbers, strings, and expressions in each cell. Users can move the cursor with arrow keys UP, DOWN, LEFT, RIGHT. Alt-Q will quit the program.
3
Define the CCell Class in “cell.h”
To save your time, you can download the main program and the constant.h file. All you need to do is design a class CCell, save it in “cell.h”, and integrate these three files to generate an executable program. Submit your “cell.h”
4
Requirements for CCell
To make it easy, let’s start with all data members public. Each cell has a data member m_Expression to store the expression. You may declare it as a character array containing MAX_EXPR_LEN bytes. A cell also has two data member "row" and "column" to indicate its location. As the convention in C++, the index starts from 0. For convenience, we also create a data member m_Coordination, which stores the text representation of the location of each cell. For example cell(0,0) is A1, cell(1,0) is A2, cell(0, 2) is C1. Don't forget to supply a constructor of this class.
5
春望 ~杜甫 國破山河在,城春草木深。 感時花濺淚,恨別鳥驚心。 烽火連三月,家書抵萬金。 白頭搔更短,渾欲不勝簪。
6
程式設計課程 核心能力 與 課程地圖
7
暨大資工系 教育目標 產業需求 實作能力 研發潛能 理論能力 人的本質 自己以外
8
暨大資工系 核心能力 基礎數理 理論 程式設計 軟體 電子元件 硬體 英文能力 團隊合作 生命品格
9
暨大資工系 課程地圖(部分) 全校共同課程14學分 通識領域課程17學分 專業選修 >= 32學分 未來發展(職涯)
10
暨大科技學院 核心能力 1.專業知識與實務技能 2.創新與獨立思考能力 3.溝通表達與團隊合作精神 4.專業倫理與社會責任認知
暨大科技學院 核心能力 1.專業知識與實務技能 2.創新與獨立思考能力 3.溝通表達與團隊合作精神 4.專業倫理與社會責任認知 5.掌握國際趨勢與全球視野
11
暨大學生 八大基本素養與核心能力 ﹙一﹚道德思辨與實踐能力 ﹙二﹚人際溝通與表達能力 ﹙三﹚獨立思考與創新能力 ﹙四﹚人文關懷與藝術涵養
﹙五﹚專業知能與數位能力 ﹙六﹚團隊合作與樂業倫理 ﹙七﹚全球視野與尊重多元文化 ﹙八﹚社區參與與公民責任
12
資訊科技‧實現創意 暨大資工‧創意先鋒 資訊科技 ‧ 實現創意 ‧ 暨大資工 ‧ 創意先鋒
13
Chapter 8 (Part 3) Native C++ Library Classes for Strings (P.510)
14
String Concatenation Good afternoon. Bob. Good afternoon. Charlie.
#include <iostream> using std::cout; int main() { char a[] = "Good afternoon. "; char b[] = "Bob. "; char c[] = "Charlie. "; char newline[] = "\n"; char str[80] = ""; strcpy(str, a); strcat(str, b); strcat(str, newline); strcat(str, a); strcat(str, c); cout << str; return 0; } Good afternoon. Bob. Good afternoon. Charlie.
15
Powerful C++ Class #include <iostream> #include <string> using std::cout; using std::string; int main() { string a = "Good afternoon. "; string b = "Bob. "; string c = "Charlie. "; string newline = "\n"; string str; str = a + b+ newline + a + c + newline; cout << str; return 0; }
16
Strings C language only has null-terminated strings which is stored as character arrays. char name[5] = "Mary"; C++ provides a string data type which is much easier to use. The class provides a bunch of powerful functions.
17
Creating String Objects
string sentence = "This sentence is false."; string sentence("This sentence is false."); string bees(7, 'b'); string bees("bbbbbbb"); string letters(bees); string part(sentence, 5, 11); string part("sentence is"); the first character is at index position 0 string names[] = { "Alice", "Bob" }; string arrays
18
Input a string Read a character string into a string object:
string sentence; cin >> sentence; However, cin will ignores leading whitespaces, and also terminates input when you enter a space, so for the input “This is a book”, only “This” is read into the object. Use the getline() function: getline(cin, sentence); ifstream fsIn("abc.txt"); getline(fsIn, sentence); the source of the input the destination for the input
19
Concatenating Strings
Use the + operator to concatenate two string objects or a string object and a string literal. #include <iostream> #include <string> using std::cout; using std::endl; using std::string; int main() { string sentence1 = "This"; string sentence2 = "That"; string combined = sentence1 + "\n" + sentence2; cout << combined << endl; return 0; } This That
20
Concatenating Strings (2)
You can also use the + operator to join a character to a string object sentence = sentence + '\n'; sentence += '\n'; sentence += "\n"; Length of a string sentence.length() // returns an integer sentence.empty() // returns true or false Ex8_12.cpp (P.513) size_t is defined using typedef statement to be equivalent to unsigned int. (P.190)
21
Accessing Strings Access a character in a string
string sentence("Too many cooks spil the broth."); for (int i = 0; i < sentence.length(); i++) { if (' ' == sentence[i]) sentence[i] = '*'; } Use the at() member function if (' ' == sentence.at(i)) sentence.at(i) = '*'; Subscripting is faster, but the validity of the index is not checked.
22
Access a substring in a string
Extract a part of an existing string object as a new string object. string sentence("Too many cooks spoil the broth."); string w = sentence.substr(4,10); // Extracts "many cooks"
23
Modifying Strings (1) Add one or more characters to the end of a string. string phrase("The higher"); string word("fewer"); phrase.append(1, ' '); // Append one space phrase.append("the "); // Append a string literal phrase.append(word); // Append a string object phrase.append(2, '!');// Append two exclamation marks When you call append(), the function returns a reference to the object, so you could write the above calls in a single statement: phrase.append(1, ' ').append("the ").append(word).append(2, '!');
24
Modifying Strings (2) Insert a string in the interior of another string: (P.517) string word("ABCDEF"); string test("==="); word.insert(3, test); // word will become "ABC===DEF" Swap the contents of two string objects: string phrase("The more the merrier."); string query("Any"); query.swap(phrase);
25
Modifying Strings (3) Replace part of a string object
string text("ABCDEF"); text.replace(2, 3, "->"); text will become “AB->F” Replacement with a null string will essentially delete that part. text = "AB->F"; text.replace(2, 2, ""); text will become “ABF”
26
Comparing Strings Operator overloading has been implemented for
== != < <= > >= When two corresponding characters are compared, their ASCII codes determine which one is less than the other. “USA” < “unique” If no character pairs are found to be different, the string with fewer characters is less. “book” < “books”
27
Ex8_13.cpp in main(): string* sort(string* strings, size_t count)
nstrings: # of input strings maxwidth: maximum length of input strings string* sort(string* strings, size_t count) Actually the return type can be void in this example.
28
Search Strings Four versions of the find() function:
string phrase("So near and yet so far"); string str("So near"); cout << phrase.find(str) << endl; // Outputs 0 (starting position) cout << phrase.find("so far") << endl; // Outputs 16 cout << phrase.find("so near") << endl; // Outputs string::npos = The function returns the value string::npos if the item was not found. The value of string::npos may vary with different C++ compilers, so you should always use string::npos and not the explicit value.
29
Search Strings (2) Searching from a specified position:
string phrase("ABCDEABCDEABCDE"); cout << phrase.find("A"); // Outputs 0 cout << phrase.find("A", 3); // Outputs 5 cout << phrase.find("A", 11); // Outputs string::npos =
30
Exercise Each line in "/home/solomon/horse.txt" contain the information in the format: Horse2 wins Horse1 wins Write a program to calculate how many times each horse wins? Horse1 wins 5 times Horse2 wins 6 times
31
Exercise Use the find() function to design an occurrence function, which will count the number of occurrences of a string in a text. int occurrence(string text, string str); Try to use a long text to test your function. Modify your function so that it is case-insensitive (i.e., both “ABC” and “aBc” matches “abc”).
32
Homework The sample code of Ex8_14.cpp does not generate the expected result. Try to find out the bug and fix it.
33
File I/O
34
Using Input/Output Files
A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide input data to a program or receive output data from a program, or both; must reside in Project directory (not necessarily the same directory as the .cpp files) must be opened before it is used.
35
C Functions for File I/O
In function-oriented programming, we use the following functions to access disk files: fopen() fclose() fread() fwrite() fprintf() In object-oriented programming, we use a well-prepared class “fstream”.
36
C++ Classes for Input / Output
stream - a sequence of characters interactive (iostream) cin - input stream associated with keyboard. cout - output stream associated with display. file (fstream) ifstream - defines new input stream (normally associated with a file). ofstream - defines new output stream (normally associated with a file).
37
Input File-Related Functions
#include <fstream> ifstream fsIn; fsIn.open("fname.txt") connects stream fsIn to the external file "fname.txt". fsIn >> c; //Behaves just like cin fsIn.close() disconnects the stream and associated file.
38
Output File-Related Functions
#include <fstream> ofstream fsOut; fsOut.open("fname.txt") connects stream fsOut to the external file "fname.txt". fsOut << c; //Behaves just like cout fsOut.close() disconnects the stream and associated file.
39
Example 1 #include <iostream> #include <fstream> using namespace std; int main() { char FirstName[30], LastName[30]; int Age; char FileName[20]; cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "Enter Age: "; cin >> Age; cout << "\nEnter the name of the file you want to create: "; cin >> FileName; ofstream Students(FileName, ios::out); Students << FirstName << "\n" << LastName << "\n" << Age; cout << "\n\n"; return 0; } The file will be created in the directory where your “.cpp” file resides. e.g. “D:\VisualStudio2010\Projects\YourProject\YourProject”
40
Example 2 #include <iostream> #include <fstream> using std::cin; using std::cout; using std::ofstream; int main() { char FirstName[30], LastName[30]; int Age; char FileName[20]; cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "Enter Age: "; cin >> Age; cout << "\nEnter the name of the file you want to create: "; cin >> FileName; ofstream Students(FileName); Students << FirstName << "\n" << LastName << "\n" << Age; Students.close(); return 0; }
41
Example 3: Output to a File
#include <fstream> #include <iostream> using std::cout; using std::endl; using std::ofstream; int main() { ofstream Student("message.txt"); Student << "HELLO\n"; Student << "HI\n"; return 0; }
42
Example 4 #include <iostream> #include <fstream> using std::cin; using std::cout; using std::ifstream; int main() { char FirstName[30], LastName[30]; int Age; char FileName[20]; cout << "Enter the name of the file you want to open: "; cin >> FileName; ifstream Students(FileName); Students >> FirstName >> LastName >> Age; Students.close(); cout << "\nFirst Name: " << FirstName; cout << "\nLast Name: " << LastName; cout << "\nEnter Age: " << Age; cout << "\n\n"; return 0; }
43
Exercise: ifstream There are 100 lines in "/home/solomon/data.txt". There is exact one integer in a line. Write a program and use the "ifstream" class to read data from this file. Calculate the sum and average of these numbers. Extend your program to handle unlimited number of lines with the following indefinite loop: while (fsIn >> n) { sum += n; count++; }
44
Exercise Download a text file containing the list members of CS101.
Write a C++ program which reads the 137 entries from this file and sort them in alphabetical order. Some students registers twice with different accounts. Write a program to find out these students. For example,
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.