Chapter 10 User Defined Simple Data Types cstring

  • Slides: 50
Download presentation
Chapter 10: User Defined Simple Data Types cstring and File I/O

Chapter 10: User Defined Simple Data Types cstring and File I/O

Define our own data types �We can define a new data type by defining

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!

typedef: user-defined simple data type � Syntax: typedef Existing. Type. Name New. Type. Name

typedef: user-defined simple data type � Syntax: typedef Existing. Type. Name New. Type. Name ; � Example: typedef char letter_grade; int main() { letter_grade; cin >> grade; if ( grade == 'A') cout << "Above 90%!" << endl; return 0; } � 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.

C++ Data Types simple integral enum structured floating array struct union class char short

C++ Data Types simple integral enum structured floating array struct union class char short int long bool float double long double address pointer reference

Enumeration Types �A user-defined data type whose domain is an ordered set of literal

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}; enumerators 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. � enum �Syntax: enum New. Type. Name {enumerator list};

Enumerators �Enumerators are ordered: � SUN < MON < TUE < WED < THU

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.

Names for enumerators enum Vowls {‘A’, ‘E’, ‘I’, ‘O’, ‘U’}; // correct? // No!

Names for enumerators enum Vowls {‘A’, ‘E’, ‘I’, ‘O’, ‘U’}; // correct? // No! Identifiers starts with a letter or underscore. enum Places {1 st, 2 nd, 3 rd}; // 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!

Type Cast and Enumerator Values enum Days {SUN = 7, MON = 1, TUE,

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! //assigning values to enumerators may break the order! Tomorrow is tuesday! // integer values continue increasing after the user-defined value.

Type Cast and Enumerator Values (2) enum Vegetables {cabbage = 4, carrot, tomato =

Type Cast and Enumerator Values (2) enum Vegetables {cabbage = 4, carrot, tomato = 2, potato}; Vegetables vege 1 = carrot, vege 2 = potato; cout << "vege 1 is: " << int (vege 1) << endl; cout << "vege 2 is: " << int (vege 2) << endl; if ( vege 1 < vege 2 ) cout << "vege 1 is smaller than vege 2!" << endl; else cout << "vege 1 is larger than vege 2!" << endl; // output: vege 1 is: 5 // integer values continue increasing after the user-defined value. vege 2 is: 3 vege 1 is larger than vege 2!

Type Cast and Output enum Data Types enum Fruits {apple, grape, pear}; int fruit;

Type Cast and Output enum Data Types enum Fruits {apple, grape, pear}; int fruit; cin >> fruit; switch (Fruits (fruit)) // use switch statement to output enumerators. { 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;

Character String 11

Character String 11

Data Type string #include <string> // C++ String class string str 1, str 2;

Data Type string #include <string> // C++ String class string str 1, str 2; // Default constructor cin >> str 1 >> str 2; cout << “str 1: ” << str 1 << endl << “str 2: ” << str 2; str 2 = str 1; str 2 = “CS 1430”; // Assigning string variables; 12

C++ Class string: compare if (str 1 == “CS 1430”) cout << “Programming in

C++ Class string: compare if (str 1 == “CS 1430”) cout << “Programming in C++”; if (str 1 > str 2) cout << “str 1 appears after str 2 in a dictionary. ”; else if (str 1 < str 2) cout << “str 1 appears before str 2 in a dictionary. ”; else cout << “str 1 is the same as str 2. ” // string comparison is character by character: // str 1 is less than str 2 // if word str 1 is listed before str 2 in a dictionary // Two string literals cannot be compared! 13

C++ Class string: length & size cout << “str 1 has “ << “

C++ Class string: length & size cout << “str 1 has “ << “ chars. ”; << str 1. length() cout << “str 2 has “ << str 2. 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: char array String is implemented as an array of char cin

C++ Class string: char array String is implemented as an array of char cin >> str 1; cout << “The first char of str 1 ” << str 1[0]; cout << “The last char of str 1 ” //<< str 1[? ]; << str 1[str 1. length() - 1]; // Change the first char of str 1 to ‘A’. str 1[0] = ‘A’; 15

C++ Class string: substring �Sub. String Function cin >> str 1; cout << “The

C++ Class string: substring �Sub. String Function cin >> str 1; cout << “The first three chars of str 1: ” << str 1. substr(0, 3); // substring starting at index 0 // with length 3 cout << “The last three chars of str 1: ” << str 1. substr(str 1. length() – 3, 3); // substring starting at index str 1. length()– 3 // with length 3 16

C++ Class string: getline(cin, str 1, ‘n’); getline(cin, str 2); // not a member

C++ Class string: getline(cin, str 1, ‘n’); getline(cin, str 2); // not a member function of class string int pos = str 1. find(“ ”); // a member function of class string str 1[pos] = ‘_’; cout << str 1; // Change the first white space to ‘_’. 17

C String: input �In C and C++, C string is a null-terminated sequence of

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 last. Name[NAME_LENGTH + 1]; // One more for the null char ‘’. cout << "Enter last name: "; cin >> last. Name; // // // No loops needed! C++ reads chars until White Characters, then inserts a ‘’. The array is treated as a string. and ended with a null char ‘’. 18

C String: output cout << "The last name is " << last. Name; //

C String: output cout << "The last name is " << last. Name; // C++ displays one char at a time // until a '' is reached. What if there is no null character? if you use cin to read last. Name directly, ‘’ was automatically inserted when reading from the input! if you assign last. Name char by char, no ‘’ will be assigned error! 19

typedef and C string const int NAME_LENGTH = 15; char last. Name[NAME_LENGTH + 1];

typedef and C string const int NAME_LENGTH = 15; char last. Name[NAME_LENGTH + 1]; typedef char name. Type[NAME_LENGTH + 1]; name. Type name 1, name 2; // same as // char name 1[NAME_LENGTH + 1], // char name 2[NAME_LENGTH + 1]; 20

C String: assignment char name 1[16], name 2[16]; // Up to 15 chars! cout

C String: assignment char name 1[16], name 2[16]; // Up to 15 chars! cout << "Enter last name: "; cin >> name 1; name 2 = name 1; // Can we do this? // NO! Cannot assign an array to an array! name 2 = “John”; // Can we do this? // NO! Cannot assign a string to an array! char name 3[] = “John”; // Can we do this? // YES! Can initialize a char array! // Same as char name 3[] = {‘J’, ’o’, ’h’, ’n’}; 21

C String: compare cin >> name 2; if (name 1 == name 2) //

C String: compare cin >> name 2; if (name 1 == name 2) // Can we do this? cout << “Same name!”; // NO! Cannot compare two char arrays string name 3; cin >> name 3; if (name 1 == name 3) // Can we do this? cout << "Same name!" << endl; // YES! Can compare a string with a char array How to compare two C strings? Use cstring functions 22

C String Functions #include <cstring> Four functions: // return the length of the char

C String Functions #include <cstring> Four functions: // return the length of the char array, // not including ‘’ // 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 str 1[], const char str 2[]); 23

C String Functions #include <cstring> char name 1[16], name 2[16]; cout << "Enter last

C String Functions #include <cstring> char name 1[16], name 2[16]; cout << "Enter last name: "; cin >> name 1; name 2 = name 1; // Valid? // NO! strcpy(name 2, name 1); // Yes! strcat(name 2, name 1); cout << name 2 << endl; cout << “name 1 has ” << strlen(name 1) << “ chars. ”; 24

Function strcmp() �The function compares two strings one char at a time, and stops

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 str 1 and str 2. �The function returns the difference of the chars at the stopping position of the two strings. Return value from strcmp(srt 1, srt 2) Result 0 str 1 the same as str 2 > 0 str 1 is larger than str 2 (later in a dictionary) < 0 str 1 is smaller than str 2 (earlier in a dictionary) str 1 “CS 143” “CS 1430” “CS 143” “CS 113” “ 100” str 2 “CS 143” “CS 1430” “CS 143” “ 99” strcmp(srt 1, srt 2) ? ? ? 25

Function strcmp() #include <cstring> char name 1[16], name 2[16]; cin >> name 1 >>

Function strcmp() #include <cstring> char name 1[16], name 2[16]; cin >> name 1 >> name 2; int result = strcmp(name 1, name 2); if (result == 0) cout << “Same string. ”; else if (result < 0) cout << “name 1 is smaller than name 2. ”; else cout << “name 1 is larger than name 2. ”; 26

Function strcpy() //-----------------------// The function has two parameters: // dest[], array of char, //

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] != ‘’; i ++) dest[i] = src[i]; return; } // Correct? 27

Function strcpy() //-----------------------// The function has two parameters: // dest[], array of char, //

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] != ‘’; i ++) dest[i] = src[i]; dest[i] = ‘’; // Copy the NULL character. return; } // Correct? 28

Function strcpy() //-----------------------// The function has two parameters: // dest[], array of char, //

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] != ‘’; i ++) dest[i] = src[i]; dest[i] = ‘’; } return; 29

Function strcpy() //-----------------------// The function has two parameters: // dest[], array of char, //

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] != ‘’) { dest[i] = src[i]; i ++; } dest[i] = ‘’; return; } 30

Function strlen() //----------------------// The function has one parameter: // str[], array of char. //

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] != ‘’) size ++; } return size; 31

Function strcmp() //---------------------------// The function has two parameters: // str 1[], array of char,

Function strcmp() //---------------------------// The function has two parameters: // str 1[], array of char, null terminated, // str 2[], array of char, null terminated. // The function returns an integer: // 0 when str 1 is the same as str 2 // positive when str 1 > str 2 // negative when str 1 < str 2. // Parameter: (in, in) //---------------------------int strcmp(const char str 1[], const char str 2[]) { int i; for (i = 0; str 1[i] != ‘’ && str 2[i] != ‘’; i ++) if (str 1[i] != str 2[i]) return (str 1[i] - str 2[i]); } 32

Function strcmp() //---------------------------// The function has two parameters: // str 1[], array of char,

Function strcmp() //---------------------------// The function has two parameters: // str 1[], array of char, null terminated, // str 2[], array of char, null terminated. // The function returns an integer: // 0 when str 1 is the same as str 2 // positive when str 1 > str 2 // negative when str 1 < str 2. // Parameter: (in, in) //---------------------------int strcmp(const char str 1[], const char str 2[]) { int i; // Can we check just str 1[i]? for (i = 0; str 1[i] != ‘’; i ++) if (str 1[i] != str 2[i]) return (str 1[i] - str 2[i]); } Very Good! 33

Function strcat() //---------------------------// The function has two parameters: // dest[], array of char, null

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] != '' ) { dest[dest_ix] = src[src_ix]; ++dest_ix; ++src_ix; } dest[dest_ix] = ''; } 34

File I/O Streams 35

File I/O Streams 35

File input in Hi. C �Run menu �Set Input File… �Load Input �Input (Interactive)

File input in Hi. C �Run menu �Set Input File… �Load Input �Input (Interactive) � (Batch) �OK �We want to know how to do it ourselves, right? 36

Standard IO: <iostream> // Header file #include <iostream> int size; float avg; cin >>

Standard IO: <iostream> // Header file #include <iostream> int size; float avg; cin >> size; // cin: Standard input stream // >>: input operator cout << "Average is " << avg; // cout: standard output stream // <<: output operator 37

Class istream // Input stream class istream { private: // Members: public: bool eof();

Class istream // Input stream class istream { private: // Members: public: bool eof(); void get(char& x); void getline(char s[], int size, char end. Char); … }; istream cin; // object of istream // connecting cin to keyboard 38

Class ostream // Output stream class ostream { private: // Members public: bool good();

Class ostream // Output stream class ostream { private: // Members public: bool good(); bool fail(); … }; ostream cout; // object of ostream // connecting cout to monitor 39

File IO: fstream // File Stream #include <fstream> // Input File Stream class ifstream

File IO: fstream // File Stream #include <fstream> // Input File Stream class ifstream { … }; // Output File Stream class ofstream { … }; 40

Class ifstream // File Stream #include <fstream> class ifstream { private: . . .

Class ifstream // File Stream #include <fstream> class ifstream { private: . . . public: void open(const char file. Name[]); // Hi. C cannot use C++ string for file. Name void close(); bool good(); bool fail(); }; bool eof(); void get(char& x); … 41

Class ofstream // File Stream #include <fstream> class ofstream { private: . . .

Class ofstream // File Stream #include <fstream> class ofstream { private: . . . public: void open(const char file. Name[]); // Not C++ string void close(); bool good(); bool fail(); … }; 42

fstream vs. iostream �Use file I/O almost the same way as using standard I/O

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

File Input Stream #include <fstream> int main() { ifstream in. File; // Open file

File Input Stream #include <fstream> int main() { ifstream in. File; // Open file // void open(const char file. Name[]); in. File. open(“P 6. IN"); // P 6. IN is in the same folder as the source file in. File. open(“J: \P 6. IN"); // P 6. IN could be any where // Escape char ‘’ // Do work } // void close(); // No parameter! in. File. close(); return 0; 44

File Input Check #include <iostream> #include <fstream> int main() { ifstream in. File; in.

File Input Check #include <iostream> #include <fstream> int main() { ifstream in. File; in. File. open(“P 6. IN"); // Check open operation if (!in. File. good()) { cout << "Error: Cannot open input file"; return 1; } // OR if (in. File. fail()) { cout << "Error: Cannot open input file!"; return 1; } } return 0; 45

File Input Stream #include <iostream> #include <fstream> using namespace std; const int MAX_SIZE =

File Input Stream #include <iostream> #include <fstream> using namespace std; const int MAX_SIZE = 10; int main() { ifstream in. File; in. File. open(“sample. Input. txt"); if (!in. File. good()) cout << "Error: Cannot open input file"; int my. Array[MAX_SIZE]; int size = 0; while ( ! in. File. eof() ) { in. File >> my. Array[size]; cout << "Element " << size + 1 << " is " << my. Array[size] << ". " << endl; size++; } in. File. close(); return 0; } 46

File Input/Output Stream #include <iostream> #include <fstream> using namespace std; const int MAX_SIZE =

File Input/Output Stream #include <iostream> #include <fstream> using namespace std; const int MAX_SIZE = 10; int main() { ifstream in. File; ofstream out. File; in. File. open(“sample. Input. txt"); if (!in. File. good()) cout << "Error: Cannot open input file"; out. File. open(“sample. Output. txt”); int my. Array[MAX_SIZE]; int size = 0; while ( ! in. File. eof() ) { in. File >> my. Array[size]; out. File << "Element " << size + 1 << " is " << my. Array[size] << ". " << endl; size++; } in. File. close(); out. File. close(); return 0; } 47

File Stream as a Function Parameter int main() { ifstream My. Input; if (!Open.

File Stream as a Function Parameter int main() { ifstream My. Input; if (!Open. File(My. Input)) return 1; // Do work } return 0; bool Open. File(ifstream& in. File) // out parameter! { char file_name[21]; cin >> file_name; // file name needs to a C string! in. File. open(file_name); } if (!in. File. good()) { cout << "Error: Cannot open input file"; return false; } else return true; 48

File I/O Summary �#include <fstream> �declare ifstream variable in. File and/or ofstream variable out.

File I/O Summary �#include <fstream> �declare ifstream variable in. File and/or ofstream variable out. File �open an input file: in. File. open(In. File. Name); �check for valid input file: in. File. good() or in. File. fail() �open an output file: out. File. open(Out. File. Name); �If Out. File. Name does not exist, create a new file. �If Out. File. Name already exists, overwrite this file. �use in. File the same way as cin; use out. File the same way as cout. �always remember to in. File. close() and out. File. close()! 49

Summary �typedef �enumerator name follows C++ naming rules. �enumerator value �type cast is useful

Summary �typedef �enumerator name follows C++ naming rules. �enumerator value �type cast is useful