Download presentation
Presentation is loading. Please wait.
Published byAlyson Matthews Modified over 8 years ago
2
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 own simple data type? Yes! Use typedef !
3
typedef: user-defined simple data type Syntax: Example: It does not actually create a new data type, just give another name for the existing data type. Sometimes, it is used to indicate how a variable represents something. typedef ExistingTypeName NewTypeName ; typedef char letter_grade; int main() { letter_grade grade; cin >> grade; if ( grade == 'A') cout << "Above 90%!" << endl; return 0; }
4
C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long double
5
Enumeration Types A user-defined data type whose domain is an ordered set of literal values expressed as identifiers. enum Days {SUN, MON, TUE, WED, THU, FRI, SAT}; enum is a keyword. This definition creates a new data type Days. Data type Days has seven possible values: SUN to SAT. They are called enumerators. Syntax: enumerators enum NewTypeName {enumerator list};
6
Enumerators Enumerators are ordered: SUN < MON < TUE < WED < THU < FRI < SAT You can compare two variables of Days type! Values of enumerators in an enum type are represented internally as integers. By default, the first enumerator = 0. Every next one increases by 1. You can assign different integer values to enumerators: enum Days {SUN = 7, MON = 1, TUE, WED, THU, FRI, SAT}; enum Vegetables {cabbage = 4, carrot, tomato, potato}; You can treat an enumerator value as a constant! The identifiers of enumerators follow C++ naming rules! Since we can treat an enumerator as a constant, the identifier usually follows the constant naming rule.
7
Names for enumerators enum Vowls {‘A’, ‘E’, ‘I’, ‘O’, ‘U’}; // correct? // No! Identifiers starts with a letter or underscore. enum Places {1st, 2nd, 3rd}; // correct? // No! Identifiers starts with a letter or underscore. enum Vegetables {cabbage, carrot, tomato, potato}; enum Fruits {apple, tomato, pear}; // correct? // No! Identifiers in the same scope must be unique!
8
Type Cast and Enumerator Values enum Days {SUN = 7, MON = 1, TUE, WED, THU, FRI, SAT}; int main() { Days today, yesterday, tomorrow; today = MON; yesterday = SUN; tomorrow = Days ( today + 1); if ( today < yesterday ) cout << "Today is before yesterday!" << endl; if ( tomorrow == TUE ) cout << "Tomorrow is tuesday!" << endl; return 0; } // output: Today is before yesterday! Tomorrow is tuesday! //assigning values to enumerators may break the order! // integer values continue increasing after the user-defined value.
9
Type Cast and Enumerator Values (2) enum Vegetables {cabbage = 4, carrot, tomato = 2, potato}; Vegetables vege1 = carrot, vege2 = potato; cout << "vege1 is: " << int (vege1) << endl; cout << "vege2 is: " << int (vege2) << endl; if ( vege1 < vege2 ) cout << "vege1 is smaller than vege2!" << endl; else cout << "vege1 is larger than vege2!" << endl; // output: vege1 is: 5 vege2 is: 3 vege1 is larger than vege2! // integer values continue increasing after the user-defined value.
10
Type Cast and Output enum Data Types enum Fruits {apple, grape, pear}; int fruit; cin >> fruit; switch (Fruits (fruit)) { case apple: cout << "apple" << endl; break; case grape: cout << "grape" << endl; break; case pear : cout << "pear" << endl; break; default : cout << "invalid" << endl; } cout << int ( Fruits ( fruit ) ) << endl; // use switch statement to output enumerators.
11
11
12
Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout << “str1: ” << str1 << endl << “str2: ” << str2; str2 = str1; str2 = “CS1430”; // Assigning string variables; 12
13
C++ Class string: compare if (str1 == “CS1430”) cout << “Programming in C++”; if (str1 > str2) cout << “str1 appears after str2 in a dictionary.”; else if (str1 < str2) cout << “str1 appears before str2 in a dictionary.”; else cout << “str1 is the same as str2.” // string comparison is character by character: // str1 is less than str2 // if word str1 is listed before str2 in a dictionary // Two string literals cannot be compared! 13
14
cout << “str1 has “ << str1.length() << “ chars.”; cout << “str2 has “ << str2.size() << “ chars.”; // length() and size() will both return // the number of characters in the string. // They are methods of class string. 14 C++ Class string: length & size
15
String is implemented as an array of char cin >> str1; cout << “The first char of str1 ” << str1[0]; cout << “The last char of str1 ” //<< str1[?]; << str1[str1.length() - 1]; // Change the first char of str1 to ‘A’. str1[0] = ‘A’; 15 C++ Class string: char array
16
SubString Function cin >> str1; cout << “The first three chars of str1: ” << str1.substr(0, 3); // substring starting at index 0 // with length 3 cout << “The last three chars of str1: ” << str1.substr(str1.length() – 3, 3); // substring starting at index str1.length()–3 // with length 3 16 C++ Class string: substring
17
getline(cin, str1, ‘\n’); getline(cin, str2); // not a member function of class string int pos = str1.find(“ ”); // a member function of class string str1[pos] = ‘_’; cout << str1; // Change the first white space to ‘_’. 17 C++ Class string: getline
18
C String: input In C and C++, C string is a null-terminated sequence of characters stored in a char array. const int NAME_LENGTH = 15; char lastName[NAME_LENGTH + 1]; // One more for the null char ‘\0’. cout << "Enter last name: "; cin >> lastName; // No loops needed! // C++ reads chars until White Characters, // then inserts a ‘\0’. // The array is treated as a string. // and ended with a null char ‘\0’. 18
19
cout << "The last name is " << lastName; // C++ displays one char at a time // until a '\0' is reached. What if there is no null character? 19 C String: output if you use cin to read lastName directly, ‘\0’ was automatically inserted when reading from the input! if you assign lastName char by char, no ‘\0’ will be assigned error!
20
typedef and C string const int NAME_LENGTH = 15; char lastName[NAME_LENGTH + 1]; typedef char nameType[NAME_LENGTH + 1]; nameType name1, name2; // same as // char name1[NAME_LENGTH + 1], // char name2[NAME_LENGTH + 1]; 20
21
char name1[16], name2[16]; // Up to 15 chars! cout << "Enter last name: "; cin >> name1; name2 = name1; // Can we do this? // NO! Cannot assign an array to an array! name2 = “John”; // Can we do this? // NO! Cannot assign a string to an array! char name3[] = “John”; // Can we do this? // YES! Can initialize a char array! // Same as char name3[] = {‘J’,’o’,’h’,’n’}; 21 C String: assignment
22
cin >> name2; if (name1 == name2) // Can we do this? cout << “Same name!”; // NO! Cannot compare two char arrays string name3; cin >> name3; if (name1 == name3) // Can we do this? cout << "Same name!" << endl; // YES! Can compare a string with a char array C String: compare How to compare two C strings? Use cstring functions 22
23
C String Functions #include Four functions: // return the length of the char array, // not including ‘\0’ // para: in int strlen(const char str[]); // copy the src array to the dest array // para: out, in void strcpy(char dest[], const char src[]); // append src to the end of dest // para: out, in void strcat(char dest[], const char src[]); // copmare two char arrays // para: in, in int strcmp(const char str1[], const char str2[]); 23
24
C String Functions #include char name1[16], name2[16]; cout << "Enter last name: "; cin >> name1; name2 = name1; // Valid? // NO! strcpy(name2, name1); // Yes! strcat(name2, name1); cout << name2 << endl; cout << “name1 has ” << strlen(name1) << “ chars.”; 24
25
Function strcmp() The function compares two strings one char at a time, and stops the first time the two strings have different chars or a null char is reached for both str1 and str2. The function returns the difference of the chars at the stopping position of the two strings. Return value from strcmp(srt1, srt2) Result 0 str1 the same as str2 > 0 str1 is larger than str2 (later in a dictionary) < 0 str1 is smaller than str2 (earlier in a dictionary) str1 str2 strcmp(srt1, srt2) “CS143” “CS143” ? “CS1430” “CS143” ? “CS143” “CS1430” ? “CS113” “CS143” ? “100” “99” ? 25
26
Function strcmp() #include char name1[16], name2[16]; cin >> name1 >> name2; int result = strcmp(name1, name2); if (result == 0) cout << “Same string.”; else if (result < 0) cout << “name1 is smaller than name2.”; else cout << “name1 is larger than name2.”; 26
27
Function strcpy() //----------------------------------------------- // The function has two parameters: // dest[], array of char, // src[], array of char. // The function copies src[] to dest[] and inserts // a null char at the end. // Parameter: (out, in) //----------------------------------------------- void strcpy(char dest[], const char src[]) { for (int i = 0; src[i] != ‘\0’; i ++) dest[i] = src[i]; return; } // Correct? 27
28
Function strcpy() //----------------------------------------------- // The function has two parameters: // dest[], array of char, // src[], array of char. // The function copies src[] to dest[] and inserts // a null char at the end. // Parameter: (out, in) //----------------------------------------------- void strcpy(char dest[], const char src[]) { for (int i = 0; src[i] != ‘\0’; i ++) dest[i] = src[i]; dest[i] = ‘\0’; // Copy the NULL character. return; } // Correct? 28
29
Function strcpy() //----------------------------------------------- // The function has two parameters: // dest[], array of char, // src[], array of char. // The function copies src[] to dest[] and inserts // a null char at the end. // Parameter: (out, in) //----------------------------------------------- void strcpy(char dest[], const char src[]) { int i; for (i = 0; src[i] != ‘\0’; i ++) dest[i] = src[i]; dest[i] = ‘\0’; return; } 29
30
Function strcpy() //----------------------------------------------- // The function has two parameters: // dest[], array of char, // src[], array of char. // The function copies src[] to dest[] and inserts // a null char at the end. // Parameter: (out, in) //----------------------------------------------- void strcpy(char dest[], const char src[]) { int i = 0; while (src[i] != ‘\0’) { dest[i] = src[i]; i ++; } dest[i] = ‘\0’; return; } 30
31
Function strlen() //--------------------------------------------- // The function has one parameter: // str[], array of char. // The function finds and returns the length of // str[], excluding the null // char at the end. // Parameter: (in) //--------------------------------------------- int strlen(const char str[]) { int size = 0; while (str[size] != ‘\0’) size ++; return size; } 31
32
Function strcmp() //------------------------------------------------------- // The function has two parameters: // str1[], array of char, null terminated, // str2[], array of char, null terminated. // The function returns an integer: // 0 when str1 is the same as str2 // positive when str1 > str2 // negative when str1 < str2. // Parameter: (in, in) //------------------------------------------------------ int strcmp(const char str1[], const char str2[]) { int i; for (i = 0; str1[i] != ‘\0’ && str2[i] != ‘\0’; i ++) if (str1[i] != str2[i]) return (str1[i] - str2[i]); } 32
33
Function strcmp() //------------------------------------------------------- // The function has two parameters: // str1[], array of char, null terminated, // str2[], array of char, null terminated. // The function returns an integer: // 0 when str1 is the same as str2 // positive when str1 > str2 // negative when str1 < str2. // Parameter: (in, in) //------------------------------------------------------ int strcmp(const char str1[], const char str2[]) { int i; // Can we check just str1[i]? for (i = 0; str1[i] != ‘\0’; i ++) if (str1[i] != str2[i]) return (str1[i] - str2[i]); } Very Good! 33
34
Function strcat() //------------------------------------------------------- // The function has two parameters: // dest[], array of char, null terminated, // src[], array of char, null terminated. // The function append src[] to the end of dest[] // Parameter: (out, in) //------------------------------------------------------ int strcat(char dest[], const char src[]) { int dest_ix = strlen(dest); int src_ix = 0; while ( src[src_ix] != '\0' ) { dest[dest_ix] = src[src_ix]; ++dest_ix; ++src_ix; } dest[dest_ix] = '\0'; } 34
35
35
36
File input in HiC Run menu Set Input File… Load Input Input (Interactive) (Batch) OK We want to know how to do it ourselves, right? 36
37
Standard IO: // Header file #include int size; float avg; cin >> size; // cin: Standard input stream // >>: input operator cout << "Average is " << avg; // cout: standard output stream // <<: output operator 37
38
Class istream // Input stream class istream { private: // Members: public: bool eof(); void get(char& x); void getline(char s[], int size, char endChar); … }; istream cin; // object of istream // connecting cin to keyboard 38
39
Class ostream // Output stream class ostream { private: // Members public: bool good(); bool fail(); … }; ostream cout; // object of ostream // connecting cout to monitor 39
40
File IO: fstream // File Stream #include // Input File Stream class ifstream { … }; // Output File Stream class ofstream { … }; 40
41
Class ifstream // File Stream #include class ifstream { private:... public: void open(const char fileName[]); // HiC cannot use C++ string for fileName void close(); bool good(); bool fail(); bool eof(); void get(char& x); … }; 41
42
Class ofstream // File Stream #include class ofstream { private:... public: void open(const char fileName[]); // Not C++ string void close(); bool good(); bool fail(); … }; 42
43
fstream vs. iostream Use file I/O almost the same way as using standard I/O Difference: Before input/output, open the file first. After input/output, always close the file. 43
44
File Input Stream #include int main() { ifstream inFile; // Open file // void open(const char fileName[]); inFile.open(“P6.IN"); // P6.IN is in the same folder as the source file inFile.open(“J:\\P6.IN"); // P6.IN could be any where // Escape char ‘\’ // Do work // void close(); // No parameter! inFile.close(); return 0; } 44
45
File Input Check #include int main() { ifstream inFile; inFile.open(“P6.IN"); // Check open operation if (!inFile.good()) { cout << "Error: Cannot open input file"; return 1; } // OR if (inFile.fail()) { cout << "Error: Cannot open input file!"; return 1; } return 0; } 45
46
File Input Stream #include using namespace std; const int MAX_SIZE = 10; int main() { ifstream inFile; inFile.open(“sampleInput.txt"); if (!inFile.good()) cout << "Error: Cannot open input file"; int myArray[MAX_SIZE]; int size = 0; while ( ! inFile.eof() ) { inFile >> myArray[size]; cout << "Element " << size + 1 << " is " << myArray[size] << "." << endl; size++; } inFile.close(); return 0; } 46
47
File Input/Output Stream #include using namespace std; const int MAX_SIZE = 10; int main() { ifstream inFile; ofstream outFile; inFile.open(“sampleInput.txt"); if (!inFile.good()) cout << "Error: Cannot open input file"; outFile.open(“sampleOutput.txt”); int myArray[MAX_SIZE]; int size = 0; while ( ! inFile.eof() ) { inFile >> myArray[size]; outFile << "Element " << size + 1 << " is " << myArray[size] << "." << endl; size++; } inFile.close(); outFile.close(); return 0; } 47
48
int main() { ifstream MyInput; if (!OpenFile(MyInput)) return 1; // Do work return 0; } bool OpenFile(ifstream& inFile) // out parameter! { char file_name[21]; cin >> file_name; // file name needs to a C string! inFile.open(file_name); if (!inFile.good()) { cout << "Error: Cannot open input file"; return false; } else return true; } File Stream as a Function Parameter 48
49
File I/O Summary #include declare ifstream variable inFile and/or ofstream variable outFile open an input file: inFile.open(InFileName); check for valid input file: inFile.good() or inFile.fail() open an output file: outFile.open(OutFileName); If OutFileName does not exist, create a new file. If OutFileName already exists, overwrite this file. use inFile the same way as cin; use outFile the same way as cout. always remember to inFile.close() and outFile.close()! 49
50
Summary typedef enum enumerator name follows C++ naming rules. enumerator value type cast is useful
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.