1 / 50

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 a new class: class Student {...}; Class is a structured data type. Can we define our own simple data type? Yes! Use typedef !.

elvin
Download Presentation

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

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 10: User Defined Simple Data Typescstring and File I/O

  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 typedefExistingTypeNameNewTypeName ; • 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 char letter_grade; int main() { letter_grade grade; cin >> grade; if ( grade == 'A') cout << "Above 90%!" << endl; return 0; }

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

  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 enumNewTypeName {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 enumVowls {‘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. Character String

  12. Data Type string #include <string> // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout << “str1: ” << str1 << endl << “str2: ” << str2; str2 = str1; str2 = “CS1430”; // Assigning string variables;

  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!

  14. C++ Class string: length & size 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.

  15. C++ Class string: char array 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’;

  16. C++ Class string: substring • 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

  17. C++ Class string: getline 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 ‘_’.

  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’.

  19. C String: output 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? 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];

  21. C String: assignment 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’};

  22. C String: compare 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 How to compare two C strings? Use cstring functions

  23. C String Functions #include <cstring> 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[]);

  24. C String Functions #include <cstring> 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.”;

  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” ?

  26. Function strcmp() #include <cstring> 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.”;

  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?

  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?

  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; }

  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; }

  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; }

  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]); return (str1[i] - str2[i]); }

  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]); return (str1[i] - str2[i]); } Very Good!

  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'; }

  35. File I/O Streams

  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?

  37. 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

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

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

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

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

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

  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.

  44. File Input Stream #include <fstream> int main() { ifstreaminFile; // 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; }

  45. File Input Check #include <iostream> #include <fstream> int main() { ifstreaminFile; 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; }

  46. File Input Stream #include <iostream> #include <fstream> using namespace std; const int MAX_SIZE = 10; int main() { ifstreaminFile; 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; }

  47. File Input/Output Stream #include <iostream> #include <fstream> using namespace std; const int MAX_SIZE = 10; int main() { ifstreaminFile; ofstreamoutFile; 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; } }

  48. File Stream as a Function Parameter int main() { ifstreamMyInput; if (!OpenFile(MyInput)) return 1; // Do work return 0; } boolOpenFile(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; }

  49. File I/O Summary • #include <fstream> • 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()!

  50. Summary • typedef • enum • enumerator name follows C++ naming rules. • enumerator value • type cast is useful

More Related