Chapter 10: User Defined Simple Data Types

Download Report

Transcript Chapter 10: User Defined Simple Data Types

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 ExistingTypeName NewTypeName ;

 Example: typedef char letter_grade; int main() { letter_grade 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 structured integral enum 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 values expressed as identifiers.

enum Days {SUN, MON, TUE, WED, THU, FRI, SAT}; enumerators  enum is a keyword.

 This definition creates a new data type Days .  Data type Days has seven possible values: SUN They are called enumerators.

to SAT . 

Syntax:

enum NewTypeName {enumerator list};

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 as integers .

type are represented internally  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! 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!

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 = 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 // integer values continue increasing after the user-defined value.

vege1 is larger than vege2!

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;

11

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

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

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.

14

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

15

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

16

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

17

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

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!

19

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

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

21

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 22

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

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

Function strcmp()

 The function compares two strings one char at a time null char is reached for both str1 and str2.

, and stops the first time the two strings have different chars or a  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

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

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

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

}

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

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

}

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

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]); 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;

// 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!

33

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

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

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

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

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 // Input File Stream class ifstream { … }; // Output File Stream class ofstream { … };

40

Class ifstream

// File Stream #include class ifstream { private: . . .

public: void void open (const char fileName[]); // HiC cannot use C++ string for fileName close (); bool good(); bool fail(); }; bool eof (); void get (char& x); …

41

Class ofstream

// File Stream #include class ofstream { private: . . .

public: void void … open (const char fileName[]); // Not C++ string close (); bool good(); bool fail(); };

42

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

File Input Check

#include #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

File Input Stream

#include #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 size++; >> myArray[size]; cout << "Element " << size + 1 << " is " << myArray[size] << "." << endl; } inFile.close(); return 0;

46

File Input/Output Stream

#include #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 << myArray[size] << "." << endl; size++; << "Element " << size + 1 << " is " } inFile.close(); outFile.close(); return 0; }

47

}

File Stream as a Function Parameter

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

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

Summary

typedef

enum

 enumerator name follows C++ naming rules.

 enumerator value  type cast is useful