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.

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved Fundamentals of Characters and Strings Character constant –Integer value represented as character.
Advertisements

Strings.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
Chapter 10.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 10/29/07CS150 Introduction to Computer Science 1 Reading from and Writing to Files Section 3.12 & 13.1 & 13.5.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Programming Strings. COMP102 Prog. Fundamentals: Strings / Slide 2 Character Strings l A sequence of characters is often referred to as a character “string”.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
C-Strings Joe Meehean. C-style Strings String literals (e.g., “foo”) in C++ are stored as const char[] C-style strings characters (e.g., ‘f’) are stored.
Elements of a C++ program 1. Review Algorithms describe how to solve a problem Structured English (pseudo-code) Programs form that can be translated into.
In Addition... To the string class from the standard library accessed by #include C++ also has another library of string functions for C strings that can.
Chapter 8 Strings and Vectors (8.1 and 8.2). An Array of characters Defined as: char firstName[20]; char firstName[] = {‘T’, ‘i’, ‘m’}; // an array of.
CSIS 123A Lecture 6 Strings & Dynamic Memory. Introduction To The string Class Must include –Part of the std library You can declare an instance like.
Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT8: Characters and Strings CS2311 Computer Programming.
Chapter 8 Arrays and Strings
EGR 2261 Unit 9 Strings and C-Strings  Read Malik, pages in Chapter 7, and pages in Chapter 8.  Homework #9 and Lab #9 due next week.
File I/O ifstreams and ofstreams Sections 11.1 &
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
1 CS161 Introduction to Computer Science Topic #13.
File Input and Output in C++. Keyboard and Screen I/O #include cin (of type istream) cout (of type ostream) Keyboard Screen executing program input data.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
File I/O 1 ifstreams and ofstreams Sections 11.1 & 11.2.
An Introduction to Programming with C++ Sixth Edition Chapter 14 Sequential Access Files.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Review Binary Numbers Bit : 0 or 1 Byte: 8 bites 256 different values 2 8 KB : 1024 bytes 2 10 bytes MB : 1024 * 1024 bytes 2 10 * 2 10 (2 20 ) bytes GB.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
Chapter 2: Introduction to C++. Language Elements Keywords Programmer-defined symbols (identifiers) Operators Punctuation Syntax Lines and Statements.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
Review for Final Exam. Contents 5 questions (20 points each) + 1 bonus question (20 points) – Basic concepts in Chapters 1-4 – Chapters 5-9 – Bonus: Chapter.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
CS 1430: Programming in C++ 1. Data Type string #include // C++ String class string str1, str2; // Default constructor cin >> str1 >> str2; cout
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
Data Types Storage Size Domain of all possible values Operations 1.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
DCT1063 Programming 2 CHAPTER 3 STRINGS Mohd Nazri Bin Ibrahim Faculty of Computer, Media & Technology TATi University College
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Today’s Lecture  I/O Streams  Console I/O  File I/O  Tools for File I/O  Sequential.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
Writing to Files and Reading From Files. Writing Data to a File Creating a new file, a.dat or.txt file #include #include // for file writing #include.
1 Arrays and Pointers The name of an array is a pointer constant to the first element. Because the array’s name is a pointer constant, its value cannot.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students File Input and Output Checking input for errors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
CS 1430: Programming in C++ 1. File Input in VS Project Properties Debugging Command Arguments quiz8-1.out We want to know how to do it ourselves, right?
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
Chapter 1.2 Introduction to C++ Programming
CS Computer Science IA: Procedural Programming
Copyright © 2003 Pearson Education, Inc.
Today’s Lecture I/O Streams Tools for File I/O
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
C++ Statements and Functions
Standard Input/Output Stream
File I/O in C++ I.
Engineering Problem Solving with C++, Etter
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
Reading from and Writing to Files
File I/O in C++ I.
Reading from and Writing to Files
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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!

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

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

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

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

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]); } 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]); } 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 open(const char fileName[]); // HiC cannot use C++ string for fileName void close(); bool good(); bool fail(); bool eof(); void get(char& x); … }; 41

Class ofstream // File Stream #include class ofstream { private:... public: void open(const char fileName[]); // 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 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 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 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

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

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

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