CHAPTER 8 USER-DEFINED SIMPLE DATA TYPES, NAMESPACES, AND THE string TYPE.

Slides:



Advertisements
Similar presentations
CHAPTER 8 USER-DEFINED SIMPLE DATA TYPES, NAMESPACES, AND THE string TYPE.
Advertisements

Chapter 7: User-Defined Functions II
Chapter 7: User-Defined Simple Data Types, Namespaces, and the string Type.
Objectives In this chapter, you will:
1 Week 1304/07/2005Course ISM3230Dr. Simon Qiu  Learn how to create and manipulate enumeration type  Become aware of the typedef statement  Learn about.
Abstract Data Types Applied Arrays: Lists and Strings Chapter
True or false A variable of type char can hold the value 301. ( F )
C++ Data Type String A string is a sequence of characters enclosed in double quotes. Examples of strings: “Hello” “CIS 260” “Students” The empty string.
1 Lecture 19:String Data Type Introduction to Computer Science Spring 2006.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
Chapter 9: Arrays and Strings
Chapter 8 Arrays and Strings
C++ Programming:. Program Design Including
Basic Elements of C++ Chapter 2.
CHAPTER 2 BASIC ELEMENTS OF C++. In this chapter, you will:  Become familiar with the basic components of a C++ program, including functions, special.
CHAPTER 8 USER-DEFINED SIMPLE DATA TYPES, NAMESPACES, AND THE string TYPE.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Data representation and Data Types Variables.
Numeric Types, Expressions, and Output 1. Chapter 3 Topics Constants of Type int and float Evaluating Arithmetic Expressions Implicit Type Coercion and.
Chapter 8 Arrays and Strings
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 8: The string Type.
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.
Chapter 2. C++ Program Structure C++ program is a collection of subprograms Subprograms in C++ are called FUNCTIONS Each function performs a specific.
Basic Elements of C++ Chapter 1.
Beginning C++ Through Game Programming, Second Edition
C++ Programming: Basic Elements of C++.
CIS-165 C++ Programming I CIS-165 C++ Programming I Bergen Community College Prof. Faisal Aljamal.
Introduction to C++ Basic Elements of C++. C++ Programming: From Problem Analysis to Program Design, Fourth Edition2 The Basics of a C++ Program Function:
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Computing and Statistical Data Analysis Lecture 2 Glen Cowan RHUL Physics Computing and Statistical Data Analysis Variables, types: int, float, double,
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
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]
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 8: Simple Data Types, Namespaces, and the string Type.
C++ Basics Programming. COMP104 Lecture 5 / Slide 2 Introduction to C++ l C is a programming language developed in the 1970s with the UNIX operating system.
1 CSC 1111 Introduction to Computing using C++ C++ Basics (Part 1)
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
CHAPTER 8 USER-DEFINED SIMPLE DATA TYPES, NAMESPACES, AND THE string TYPE.
Bill Tucker Austin Community College COSC 1315
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 8: Namespaces, the class string, and User-Defined Simple Data Types.
C++ Lesson 1.
Review 1.
Chapter Topics The Basics of a C++ Program Data Types
Computer Programming BCT 1113
Chapter 1.2 Introduction to C++ Programming
Objectives In this chapter, you will:
Objectives In this chapter, you will:
Enumeration Type Data type: a set of values with a set of operations on them Enumeration type: a simple data type created by the programmer To define an.
Computing and Statistical Data Analysis Lecture 2
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Basic Elements of C++.
Basic Elements of C++ Chapter 2.
11/10/2018.
Data Types Chapter 8.
Chapter 8: The string Type
Review for Final Exam.
Wednesday 09/23/13.
Chapter 4: Control Structures I (Selection)
Engineering Problem Solving with C++, Etter
Review for Final Exam.
Chapter 2: Introduction to C++.
2. Second Step for Learning C++ Programming • Data Type • Char • Float
Engineering Problem Solving with C++ An Object Based Approach
Objectives In this chapter, you will:
Presentation transcript:

CHAPTER 8 USER-DEFINED SIMPLE DATA TYPES, NAMESPACES, AND THE string TYPE

In this chapter, you will:  Learn how to create and manipulate your own simple data type—called the enumeration type  Become aware of the typedef statement  Learn about the namespace mechanism  Explore the string data type, and learn how to use the various string functions to manipulate strings

ENUMERATION TYPE  C++ allows the user to user defined simple data type, enumeration type.  The syntax for enumeration type is: enum typeName{value1, value2,...}; where value1, value2, … are identifiers. Example enum colors{brown, blue, red, green, yellow}; brown has the value of 0,blue(1),red(2),green(3),yellow(4) //Illegal enumeration types enum grades{'A', 'B', 'C', 'D', 'F'}; enum places{1st, 2nd, 3rd, 4th}; Declaring Variables When Defining the Enumeration Type enum coins{penny, nickel, dime, halfDollar,dollar}change,usCoins; enum grades{A,B,C,D,F} courseGrade; Example 8-4 enum mathStudent{John, Bill, Cindy, Lisa, Ron}; enum compStudent{Susan, Cathy, John, William}; //Illegal  Suppose that these statements are in the same program in the same block.  The second enumeration type, compStudent, is not allowed because the value John was used in the previous enumeration type mathStudent.

Defining enumeration type enum sports{basketball, football, hockey,baseball, soccer,volleyball}; Declaring Variables sports popularSport, mySport; Assignment popularSport = football; mySport = popularSport;  No arithmetic operation is allowed on enumeration type. mySport = popularSport + 2; //illegal popularSport = football + soccer; //illegal popularSport = popularSport * 2; // illegal  Also, the increment and decrement operations are not allowed on enumeration types.  The following statements are illegal; popularSport++; //illegal popularSport--; //illegal

 Consider the following statements: popularSport = football; popularSport = static_cast (popularSport + 1);  After the second statement, the value of popularSport will be hockey. The following statements results in storing basketball in popularSport. popularSport = football; popularSport = static_cast (popularSport - 1); Relational Operators football <= soccer is true hockey > basketball is true baseball < football is false Functions and Enumeration Types  Enumeration type can be passed as parameters to functions either by value or by reference.  A function can return a value of the enumeration type.

Example 8-5 enum courses{algebra, basic, pascal, cpp,philosophy, analysis, chemistry,history}; courses readCourses() { courses registered; char ch1,ch2; cin>>ch1>>ch2; //read two characters switch(ch1) { case 'a': if(ch2 == 'l') registered = algebra; else registered = analysis; break; case 'b': registered = basic; break; case 'c': if(ch2 == 'h') registered = chemistry; else registered = cpp; break; case 'h': registered = history; break; case 'p': if(ch2 == 'a') registered = pascal; else registered = philosophy; break; default: cout<<"Illegal input."<<endl; } return registered; } //end readCourses

 Enumeration type can be output indirectly as follows: void printEnum(courses registered) { switch(registered) { case algebra: cout<<"algebra"; break; case analysis: cout<<"analysis"; break; case basic: cout<<"basic"; break; case chemistry: cout<<"chemistry"; break; case cpp: cout<<"cpp"; break; case history: cout<<history"; break; case pascal: cout<<"pascal"; break; case philosophy: cout<<"philosophy"; } //end switch } //end printEnum

Anonymous Data Types  A data type in which values are directly specified in the variable declaration with no type name is called an anonymous type. enum {basketball, football, baseball, hockey} mysport;  Creating an anonymous type has drawbacks.  We cannot pass an anonymous type as a parameter to a function.  A function cannot return a value of an anonymous type.  Values used in one anonymous type can be used in another anonymous type, but variables of those types are treated differently. enum {English, French, Spanish, German, Russian} languages; enum {English, French, Spanish, German, Russian} foreignLanguages; languages = foreignLanguages; //illegal

The typedef Statement  In C++, you can create synonyms or aliases to a previously defined data type by using the typedef statement. Example 8-6  The following statement creates an alias, integer, for the data type int. typedef int integer;  The following statement creates an alias, real, for the data type double. typedef double real; Example 8-7 typedef int Boolean;//Line 1 const Boolean True = 1; //Line 2 const Boolean False = 0; //Line 3 Boolean flag;//Line 4 flag = True;

 In July 1998, ANSI/ISO standard C++ was officially approved.  Most of the recent compilers are also compatible with ANSI/ISO standard C++.  In previous chapters, we mainly dealt with standard C++ and briefly introduced the features of ANSI/ISO standard C++.  For most part the two standards are the same. In this chapter, we discuss some of the features of ANSI/ISO standard C++ language that are not available in standard C++. Namespaces  When a header file, such as iostream, is included in a program, the global identifiers in the header file also become the global identifiers in the program.  If a global identifier in a program has the same name as one of the global identifiers in the header file, the compiler will generate syntax error (such as identifier redefined).  The same problem can occur if a program uses third party libraries.  To overcome this problem, third party vendors begin their global identifiers with a special symbol.  Since compiler vendors begin their global identifier with _ (under score), to avoid linking errors do not begin identifiers in your program with _ (under score).  ANSI/ISO standard C++ attempts to solve this problem of overlapping global identifier names with the namespace mechanism.

Example 8-8 namespace globalType { const int n = 10; const double rate = 7.50; int count = 0; void printResult(); } defines globalType to be a namespace with four members.  The scope of a namespace member is local to the namespace.  There are usually two ways a namespace member can be accessed outside the namespace.  To access the member rate of the namespace globalType, the following statement is required: globalType::rate  To access the member printResult (which is a function), the following statement is required: globalType::printResult();  To simplify the accessing of a namespace member, C++ provides the use of the statement using. Syntax: using (a) To simplify the accessing of all namespace members: using namespace namespace_name; ( b) To simplify the accessing of a specific namespace member: using namespace_name::identifier;

Example 8-12 include using namespace std; int t; double u; namespace exp {int x; char t; double u; void printResult(); } using namespace exp; int main() { int one; double t; double three; //To access global t in main, we use ::t //To access t within namespace “exp”, use exp::t //To access x from “exp”, you can use x or exp::x //To call function printResult, use printResult() or exp::printResult() } void exp::printResult() {. }

 The using statement using namespace globalType; simplifies the accessing of all members of the namespace globalType  The statement using globalType::rate; simplifies the accessing of the member rate of the namespace globalType.  In C++, using is a reserved word.  The using statement is usually put after the namespace declaration. After the using statement, to access a namespace member it is not necessary to precede the namespace_name and the scope resolution operator before the namespace member. If a namespace member and a global identifier in a program have the same name, to access this namespace member in the program, the namespace_name and the scope resolution operator must precede the namespace member. If a namespace member and an identifier in a block have the same name, to access this namespace member in the block, the namespace_name and the scope resolution operator precedes the namespace member.

Example 8-9 #include using namespace std;. int main() {. }. In this example, we can refer to global identifiers of the header file iostream, such as cin, cout, and endl, without using the prefix std:: before the identifier name. The obvious restriction is that the block (or the function) where the global identifier (of the header file iostream ) is referred must not contain any identifier with the same name as this global identifier. Example 8-11 #include. int main() { using namespace std;. }. In this example, the function main can refer to the global identifiers of the header file iostream without using the prefix std:: before the identifier name. Since the using statement appears inside the function main, other functions (if any) should use the prefix std:: before the name of the global identifier of the header file iostream unless the function also has a similar using statement.

The string Type To use the data type string, the program must include the header file string #include The statement string str1= "Hello there”, str2, str3; declares str1,str2 and str3 to be string variable and also initializes str1 to " Hello there ". The position of the first character, H, in str1 is 0, the position of the second character, ’e', is 1, and so on. Each string variable is capable of storing (just about) any size string. Binary operator + (to allow the string concatenation operation), and the array index (subscript) operator [], have been defined for the data type string. str2 = “Day” str3 = str1 + ”. ” + “Sunny” + ‘ ‘ + str2; stores the string ”Hello there. Sunny Day" into str3. str1[6] = 'T'; replaces the character t with the character T.

The data type string has a data type, string::size_type, and a named constant, string::npos, associated with it. string::size_type An unsigned integer (data) type string::npos The maximum value of the (data) type string::size_type, a number such as on many machines

The length Function  The length function returns the number of characters currently in the string.  The value returned is an unsigned integer.  The syntax to call the length function is: strVar.length() where strVar is variable of the type string.  The function length has no arguments. String name = “Wojciechowski”; name.length() would return 13

The size Function  The function size is same as the function length.  Both these functions return the same value.  The syntax to call the function size is: strVar.size() where strVar is variable of the type string.  As in the case of the function length, the function size has no arguments.

The find Function The find function searches a string to find the first occurrence of a particular substring and returns an unsigned integer value (of type string::size_type ) giving the result of the search. The syntax to call the function find is: strVar.find(strExp) where strVar is a string variable and strExp is a string expression evaluating to a string. The string expression, strExp, can also be a character. If the search is successful, the function find returns the position in strVar where the match begins. For the search to be successful, the match must be exact. If the search is unsuccessful, the function returns the special value string::npos ( “not a position within the string”). string sentence,str; string::size_type position; sentence = "It is cloudy and warm."; str = "cloudy"; StatementEffect cout<<sentence.find("is")<<endl; Outputs 3 cout<<sentence.find('s')<<endl; Outputs 4 cout<<sentence.find(str)<<endl; Outputs 6 position = sentence.find("warm"); Assigns 17 to position

The substr Function The substr function returns a particular substring of a string. The syntax to call the function substr is: strVar.substr(expr1,expr2) where expr1 and expr2 are expressions evaluating to unsigned integers. The expression expr1 specifies a position within the string (starting position of the substring). The expression expr2 specifies the length of the substring to be returned.

string sentence; stringstr; sentence = "It is cloudy and warm."; Statement Effect cout<<sentence.substr(0,5) Outputs: It is <<endl; cout<<sentence.substr(6,6) Outputs: cloudy <<endl; cout<<sentence.substr(6,16) Outputs: cloudy and warm. <<endl; cout<<sentence.substr(3,6) Outputs: is clo <<endl; str = sentence.substr(0,8); str = "It is cl" str = sentence.substr(2,10); str = " is cloudy"

The Function swap  The function swap is used to swap—that is, interchange—the contents of two string variables.  The syntax to use the function swap is strVar1.swap(strVar2) ; where strVar1 and strVar2 are string variables.  Suppose you have the following statements: string str1 = "Warm"; string str2 = "Cold";  After the following statement executes, the value of str1 is "Cold" and the value of str2 is "Warm". str1.swap(str2);