- •1.3.1 Введение 13
- •1.5.1 Введение 37
- •2. Introduction to Variables 69
- •3. Data Types 72
- •4. Techniques of Using Variables 90
- •5. Introduction to Classes 115
- •5.4.1 Introduction 129
- •6. Classes and Memory Management 131
- •6.1.1 Native References 131
- •6.5.1 Introduction 140
- •7. Classes Combinations and Inheritance 152
- •7.2.1 Introduction 165
- •7.3.1 Introduction 171
- •8. Data Input/Output, Reading, and Formatting 173
- •8.1.1 Introduction 173
- •8.5.1 Introduction 189
- •8.6.1 Introduction 195
- •9. Introduction to Functions 201
- •10. Details on Passing Arguments 225
- •10.3.1 Introduction 237
- •11. Classes and Functions 242
- •11.1.2 Practical Learning: Introducing Data Reading 243
- •11.5.1 Introduction 264
- •12. Classes and their Methods 268
- •12.1.2 Practical Learning: Introducing Data Reading 268
- •12.4.1 Introduction 284
- •13. Class Construction and Destruction 290
- •13.3.1 Introduction 311
- •14. The Properties of a Class 315
- •14.1.1 Introduction 315
- •15. Function Pointers and Delegates 337
- •15.1.1 Introduction 337
- •15.3.1 Introduction 346
- •16. Introduction to Conditions 359
- •16.1.1 Introduction 359
- •16.2.1 Introduction 369
- •25.3.1 Introduction 543
- •26. Multi-Dimensional Arrays 556
- •26.1.1 Introduction 556
- •26.2.1 Introduction 566
- •27.1.1 Introduction 595
- •34. Введение в коллекции 743
- •35. Основы коллекций платформы .Net (Fundamentals of .Net Support For Collections) 779
- •36. Встроенные интерфейсы коллекций 797
- •37. Встроенные классы коллекций 841
- •1.1Основы
- •1.1.1Введение в с
- •1.1.2Библиотека Win32
- •1.1.4Библиотека mfc
- •1.1.6Microsoft Visual Basic
- •1.2The Microsoft .Net Framework
- •1.2.1 Введение
- •1.2.2 Помощь сом
- •1.3.1Введение
- •1.3.2Компилятор
- •1.3.3Компилятор cl
- •1.4.1Функция main()
- •Int main()
- •1.4.2Консольный ввод и вывод
- •Void main()
- •Int X; // Целочисленная переменная X
- •1.4.3Директива препроцессора #pragma region
- •1.4.4Использование дескрипторов
- •Void Handles()
- •1.4.5Одномерные массивы
- •Void SingleDimensional()
- •1.4.6Многомерные массивы
- •Void CreateArr2()
- •Void CreateJaggedArray()
- •1.4.7Передача массивов функциями
- •1.4.8Классы значения
- •1.4.9Классы ссылки
- •1.4.10Интерфейсы
- •1.4.11Абстрактные классы
- •Void Foo2(){} // и так тоже можно
- •Virtual int Foo()override {return 1024;}
- •Void Abstract()
- •1.4.12Запечатанные классы и виртуальные функции
- •Void Sealed()
- •1.4.13 Видимость компонентов классов и структур
- •1.4.14Свойства
- •Void SimpleIndexProp()
- •Value class p4
- •Int Value;
- •Void set(int X, int value)
- •Void DifficultIndexedProperty()
- •Int Value;
- •Void set(int X, int value)
- •Void DefaultIndexedProperty()
- •1.4.15Деструкторы классов
- •Value class DestructorValue
- •Void SimpleDestructorDemo()
- •Void DerivedClassDestructorDemo()
- •Void Destructors()
- •1.4.16 Приведение типов
- •Void DynamicCast()
- •If(icomp)
- •Void SafeCast()
- •Void ExplicitTypeConversion()
- •Void Casting()
- •1.4.17 Класс Array
- •IStructuralComparable, iStructuralEquatable
- •Void DemoArray()
- •1.4.18 Введение в коллекции
- •Void DemoArrayList()
- •1.5.1Введение
- •Include file.H
- •1.5.3Создание консольного приложения
- •1.5.4Открытие проекта
- •1.5.7Start Without Debugging
- •1.5.8Code Comments
- •Int main()
- •Int main()
- •I can write anything I want in it */
- •1.5.9Indentation
- •Int main()
- •I can write anything I want in it */
- •1.5.10Escape Sequences
- •1.6Введение в классы
- •Int protect()
- •Int main()
- •1.7.1Source Files
- •1.7.2Practical Learning: Creating a Source File
- •1.7.3Header Files
- •1.7.4Practical Learning: Creating a Header File
- •Int ShowWelcome();
- •Int cProperty::ShowWelcome()
- •1.7.5Assemblies
- •1.7.6Applications
- •1.7.7The Public and Private Objects of an Assembly
- •1.7.8Practical Learning: Controlling the Assembly Access of a Class
- •1.7.9Creating a Class
- •1.7.10Practical Learning: Creating a Class
- •1.8The Code Editor
- •1.8.1 Description
- •1.8.2The Tabs Bar
- •1.8.3The Scopes Combo Box
- •1.8.4The Functions Combo Box
- •1.8.5Code Colors
- •1.9The Solution Explorer
- •1.9.1 Introduction
- •1.9.2 Using the Solution Explorer
- •1.10The Class View
- •1.10.1Introduction
- •1.10.2Using the Class View
- •1.11Namespaces and Code Directives
- •1.11.1Introduction
- •1.11.2Practical Learning: Including a Class in a Namespace
- •1.11.3Using a Namespace
- •Int drive()
- •Int main()
- •Int main()
- •1.11.4Using Various Namespaces
- •Int drive()
- •Int showroof()
- •Int drive()
- •Int main()
- •Int drive()
- •Int main()
- •Int drive()
- •Int main()
- •1.11.5Nesting Namespaces
- •Int main()
- •Int main()
- •1.11.6Built-In Namespaces
- •1.11.6.1 The System Namespace
- •Int main()
- •1.11.6.2The std Namespace
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •1.12C Routines
- •Int main()
- •1.13Primary Details of Program Structure
- •1.13.1Preprocessors: #include
- •1.13.2Preprocessors: #define
- •Int main()
- •1.14Pragma Directives
- •1.14.1 Introduction
- •1.14.2Open Once
- •2. Introduction to Variables
- •2.1Introduction
- •2.2The Stack
- •2.3Variable Declaration
- •2.5Keywords
- •Internal initonly interface literal long
- •Value virtual void volatile wchar_t
- •3.Data Types
- •3.1Variable Initialization
- •3.2Introduction to Data Types
- •3.3Practical Learning: Introducing Data Types Applications
- •Int main()
- •3.4Integers
- •3.4.1Signed and Unsigned Numbers
- •3.4.2Bytes
- •Int main()
- •Int main()
- •3.4.3Practical Learning: Declaring a Byte Variable
- •Int main()
- •3.4.4Short Variables
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •3.4.5Integral Variables
- •Int main()
- •3.4.6Practical Learning: Declaring Unsigned Variables
- •3.4.7Long Integers
- •Int main()
- •3.4.8Practical Learning: Declaring Long Integers
- •Int main()
- •3.4.9Initializing an Integral Variable
- •3.5Characters
- •3.5.1 Symbolic Characters
- •Int main()
- •Int main()
- •3.5.2Unicode Characters
- •Int main()
- •Int main()
- •3.5.3Practical Learning: Using Character Variables
- •Int main()
- •3.6The String: a List of Characters
- •Int main()
- •3.7Decimal Numbers
- •3.7.1Floating-Point Variables
- •Int main()
- •3.7.2Practical Learning: Using a Single-Precision Variables
- •Int main()
- •3.7.3Double-Precision Variables
- •Int main()
- •3.7.4Practical Learning: Using a Single-Precision Variables
- •Int main()
- •3.7.5Initializing a Double-Precision Variable
- •Int main()
- •Int main()
- •3.8Variable Reference
- •3.8.1 The typedef Type Definition
- •Int main()
- •Int main()
- •3.9Native References
- •Int &Mine;
- •Int main()
- •Int main()
- •Its reference: 228
- •Int main()
- •Its reference: 228
- •Its reference: -15008
- •Its reference: 28114
- •Int main()
- •Int main()
- •3.10A Tracking Reference (отслеживаемая ссылка)
- •Int main()
- •Int % PropertyValue;
- •Int main()
- •4. Techniques of Using Variables
- •4.1 Constant Values
- •4.1.1 Introduction
- •Int main()
- •Int main()
- •4.1.2Custom Constants
- •Int main()
- •Int main()
- •4.1.3Language Constants
- •Int main()
- •4.1.4Using #define
- •Int main()
- •Int main()
- •4.2Pointer Types
- •4.2.1 Introduction
- •Int main()
- •4.2.2Pointer Declaration
- •Int main()
- •Int *Number;
- •4.2.3Pointer Initialization
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int *Number;
- •Int main()
- •Int *Number;
- •4.2.4A Pointer to a Pointer
- •Int main()
- •Int *pointer;
- •Int main()
- •Int *pointer;
- •Int **pointerToPointer;
- •Int main()
- •Int *pointer;
- •Int **pointerToPointer;
- •Int main()
- •Int *pointer;
- •Int **pointerToPointer;
- •4.2.5Type Defining a Pointer
- •Int *pAge;
- •4.3Pointers and Memory Management
- •4.3.1 Introduction
- •Int main()
- •Int main()
- •Int main()
- •4.3.2The new Operator
- •Int main()
- •4.3.3Practical Learning: Introducing Pointers
- •Int main()
- •4.3.4The delete Operator
- •Int main()
- •4.3.5Practical Learning: Deleting Pointers
- •Int main()
- •4.4Handle Types
- •4.4.1 Introduction
- •4.4.2A Tracking Reference
- •Int main()
- •Int main()
- •4.4.3Creating a Handle (дескриптор)
- •Int main()
- •Int main()
- •Item Price:
- •4.5Using the Garbage Collector
- •Int main()
- •Int main()
- •Item Price: 148.95
- •Int main()
- •Int main()
- •Item Price: 148.95
- •Int main()
- •Int main()
- •Int main()
- •4.5.1Practical Learning: Using Handles
- •Int main()
- •5. Introduction to Classes
- •5.1 A Review of Classes
- •5.1.1 Introduction
- •Int main()
- •Int Bedrooms;
- •Int YearBuilt;
- •5.1.2Practical Learning: Introducing Classes
- •Int main()
- •5.2Creating a Class
- •5.2.1Practical Learning: Creating a Class
- •5.3Value Types
- •5.3.1 Introduction
- •5.3.2Practical Learning: Creating a Value Class
- •5.3.3Creating a Value Type
- •5.3.4Techniques of Initializing an Object
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •Int Bedrooms;
- •Int YearBuilt;
- •5.3.5Practical Learning: Initializing an Object
- •Int main()
- •5.3.6Class Members Levels of Access
- •Int Bedrooms;
- •Int YearBuilt;
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •5.3.7Practical Learning: Controlling the Access to a Class
- •5.3.8Type-Defining a Class
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •5.3.9Constant Objects
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •5.4Union
- •5.4.1Introduction
- •Int YearBuilt;
- •Int YearBuilt;
- •Int main()
- •5.4.2Using a Union
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •6.2Introduction to Pointers to Classes
- •6.2.1Practical Learning: Introducing Pointers to Classes
- •6.2.2Accessing the Members of a Pointer to a Class
- •Int main()
- •Int main()
- •6.2.3Practical Learning: Accessing the Members of a Pointer to a Class
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •6.3Allocating Memory on the Native Heap
- •Int main()
- •6.3.1Practical Learning: Allocating Memory on the Native Heap
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •Int main()
- •6.3.3Practical Learning: De-Allocating Memory from the Native Heap
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •6.4Classes and Pointers to Pointers
- •6.4.1Declaring a Pointer to Pointer
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •6.5Handle Types
- •6.5.1 Introduction
- •6.5.2Practical Learning: Introducing Handles
- •Int main()
- •6.5.3A Tracking Reference
- •Int main()
- •6.5.4Creating a Handle
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •6.5.5Practical Learning: Creating a Handle
- •Int main()
- •6.6Reference Types
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •6.6.1Practical Learning: Creating a Reference Class
- •6.6.2Accessing the Members of a Handle
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •6.6.3Using the Garbage Collector
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •6.6.4Practical Learning: Initializing a Handle
- •Int main()
- •7.Classes Combinations and Inheritance
- •7.1Class Combinations (агрегирование классов)
- •7.1.1 A Class as a Member Variable
- •Int Bedrooms;
- •Int YearBuilt;
- •Int main()
- •Int main()
- •7.1.2Practical Learning: Using an Object as a Field
- •7.1.3Introduction to Strings
- •Int main()
- •Int main()
- •7.1.4Practical Learning: Using String Variables
- •7.1.5A String as a Member Variable of a Class
- •7.1.6Practical Learning: Using Strings as Fields
- •7.2Inheritance
- •7.2.1 Introduction
- •7.2.2Practical Learning: Introducing Inheritance
- •7.2.3Inheriting From a Class
- •Int Bedrooms;
- •Int YearBuilt;
- •Int Bedrooms;
- •Int YearBuilt;
- •Int Condition;
- •7.2.4Practical Learning: Inheriting From a Class
- •7.2.5The protected Access Level
- •Int Bedrooms;
- •Int YearBuilt;
- •7.2.6Namespaces and Inheritance
- •7.3The Object Class
- •7.3.1 Introduction
- •7.3.2An Object as a Handle
- •Int main()
- •Int main()
- •7.3.3Inheriting from the Object Class
- •7.3.4Practical Learning: Inheriting From the Object Class
- •8.Data Input/Output, Reading, and Formatting
- •8.1 Displaying Data
- •8.1.1 Introduction
- •8.1.2General Display With cout, Write(), and WriteLine()
- •Int main()
- •Int main()
- •8.1.3Data Display With puts()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •8.2.2Filling the Empty Space
- •Int main()
- •Int main()
- •8.2.3The dec, hex, and oct Operators
- •Int main()
- •Int main()
- •8.2.4The uppercase Attribute
- •8.2.5Setting the I/o Flag
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •8.2.7C How to Display Data
- •Int main()
- •Int main()
- •8.3Data Input
- •8.3.1Using cin
- •Int main()
- •Int Natural;
- •8.3.2C How to Input Data
- •8.4Accessories
- •8.4.1Exiting a Program
- •Int main()
- •8.4.2Aborting a Program
- •8.4.3Terminating a Program
- •8.4.4Clearing the Screen
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •Int main()
- •8.5.1 Introduction
- •8.5.2Practical Learning: Introducing Data Reading
- •Int Bedrooms;
- •Int YearBuilt;
- •Int Condition;
- •Int main()
- •8.5.3String Value Request
- •Int main()
- •8.5.4Character and Number Request
- •Int main()
- •Int Number;
- •8.5.5Practical Learning: Requesting Data
- •8.6Formatting Data Display
- •8.6.1 Introduction
- •Int main()
- •8.6.2Conversion To String
- •Int main()
- •8.6.3Number Formatting
- •Int main()
- •8.6.4Line Formatting
- •Int main()
- •8.6.5Practical Learning: Formatting Data
- •Int main()
- •9. Introduction to Functions
- •9.1 Functions
- •9.1.1 Definition
- •9.1.2Fundamentals of Creating a Function
- •Void Introduction() { Console::WriteLine(l"The Wonderful World of
- •Void Introduction()
- •Int main()
- •9.1.3Calling a Function
- •Void Introduction()
- •Int main()
- •Introduction();
- •Int main()
- •Void IdentifyHouse();
- •Void IdentifyHouse()
- •9.1.4Practical Learning: Introducing Functions
- •Void CreateAndShowProperty()
- •Int condition;
- •9.1.5Inline Functions
- •9.2Techniques of Returning a Value
- •9.2.1 Returning a Primitive Type
- •Int main()
- •9.2.2Practical Learning: Returning a Primitive Type
- •Int GetPropertyCondition()
- •Int condition;
- •Void CreateAndShowProperty()
- •Int condition;
- •Int main()
- •9.2.3Returning a Native Reference
- •Int main()
- •9.2.4Returning a Tracking Reference
- •Int main()
- •9.2.5Returning a Pointer
- •Int main()
- •9.2.6Returning a Handle
- •9.2.7Practical Learning: Returning a Handle
- •Void CreateAndShowProperty()
- •Int main()
- •9.3Introduction to Functions Parameters
- •9.3.1 Overview of Parameters
- •Int main()
- •9.3.2Arguments to a Function
- •Void SetGender(__wchar_t a);
- •Void CalculateRateAmount(double price, double rate)
- •9.3.3Practical Learning: Introducing Functions
- •Void ShowProperty(long propNbr, int cond, Byte levels,
- •9.3.4Static Variables
- •Void Starter(int y)
- •Int main()
- •Void Starter(int y)
- •Int main()
- •Void Starter(int y)
- •Int main()
- •10.Details on Passing Arguments
- •10.1 Common Techniques of Using Parameters
- •10.1.1 Function Overloading
- •Int main()
- •10.1.2Default Arguments
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •10.1.3Constant Arguments
- •Int main()
- •10.2Passing Arguments by Reference
- •10.2.1 Passing by Native Reference
- •Void Area(double &Side); // The argument is passed by reference
- •Void Area(double &);
- •10.2.2Passing by Constant Reference
- •Void DisplayResult(const double OrigPrice, const double DiscAmt,
- •10.2.3Passing by Tracking Reference
- •10.3Passing a Pointer as Argument
- •10.3.1 Introduction
- •Int main()
- •Int main()
- •Int main()
- •10.3.2Constant Pointers as Arguments
- •Int main()
- •10.3.3Passing a Pointer to a Pointer
- •10.3.4Passing an Argument as a Reference to a Pointer
- •Int main()
- •10.3.5Passing an Argument as a Handle
- •Int main()
- •11.Classes and Functions
- •11.1 Returning a Class Type
- •11.1.1 Returning a Tracking Reference
- •Int Doors;
- •Int Year;
- •Int main()
- •11.1.2Practical Learning: Introducing Data Reading
- •Int Bedrooms;
- •Int YearBuilt;
- •Int Condition;
- •Int main()
- •11.1.3Returning a Handle
- •11.1.4Practical Learning: Returning a Handle
- •Int main()
- •11.2Passing a Class Type
- •11.2.1 Passing a Tracking Reference
- •Void DescribeProperty(cHouse % home);
- •Void Show(cCar % car)
- •11.2.2Passing a Handle
- •11.2.3Practical Learning: Passing a Handle
- •Int main()
- •11.2.4The Effect of Passing a Class as a Tracking Reference or as a Handle
- •Int Doors;
- •Int Year;
- •Int main()
- •11.2.5Passing a Handle as a Reference
- •Int Doors;
- •Int Year;
- •Int main()
- •Int Doors;
- •Int Year;
- •Int main()
- •11.3Using the String Class
- •11.3.1 Returning a String
- •Int main()
- •11.3.2Passing a String
- •Int main()
- •11.4Introduction to the Methods of a Class
- •11.4.1 Methods Fundamentals
- •11.4.2Practical Learning: Introducing Methods
- •Int main()
- •11.4.3Method Local Definition
- •Int Doors;
- •Int Year;
- •Void Build()
- •Int main()
- •11.4.4Practical Learning: Implementing a Method Locally
- •Void CreateStoreItem()
- •11.4.5Method Global Definition
- •Int Doors;
- •Int Year;
- •Void Build()
- •Void Show();
- •Void cCar::Show()
- •Int main()
- •11.4.6Practical Learning: Implementing Methods Globally
- •Void CreateStoreItem();
- •Void ItemDescription();
- •Void cStoreItem::CreateStoreItem()
- •Void cStoreItem::ItemDescription()
- •Int main()
- •Item Number: 624406
- •Item Number: 624406
- •11.4.7Inline Methods
- •11.5Class and Self Return
- •11.5.1 Introduction
- •Int NumberOfBedrooms;
- •Int YearBuilt;
- •11.5.2This Pointer
- •Void cHouse::Show()
- •11.5.3Practical Learning: Using the this Pointer
- •Void cStoreItem::CreateStoreItem()
- •0 If no discount): ");
- •Void cStoreItem::ItemDescription()
- •12.1.3Constant Arguments
- •Int main()
- •12.1.4Practical Learning: Passing Constant Arguments
- •0 If no discount): ");
- •Item Number: 204066
- •Item Number: 204066
- •12.1.5Private Methods
- •Void Show();
- •Void cBox::Show()
- •Int main()
- •12.1.6Protected Methods
- •12.2Static Members of a Class
- •12.2.1 Static Member Variables
- •Void cCar::Show()
- •Int main()
- •12.2.2Static Methods
- •Int Doors;
- •Int Year;
- •Void Build();
- •Int Doors;
- •Int Year;
- •Int main()
- •Int Doors;
- •Int Year;
- •Int main()
- •12.3Classes and Constants
- •12.3.1 Static Constants
- •Inside a ref class or value type
- •12.3.2Literal Constants
- •12.4Class Nesting
- •12.4.1 Introduction
- •12.4.2Implementing Methods of a Nested Class
- •13. Class Construction and Destruction
- •13.1 Class Construction
- •13.1.1 Method Initializer
- •Int Type;
- •Int Color;
- •Int main()
- •Int Type;
- •Int Color;
- •Void Initializer(int type, int color, __wchar_t arrange,
- •Void cFlower::Initializer(int tp, int clr,
- •13.1.2Practical Learning: Introducing Constructors
- •Int main()
- •13.1.3Default Constructor
- •Int Type;
- •Int Color;
- •Int Type;
- •Int Color;
- •Int main()
- •Int main()
- •Int Type;
- •Int Color;
- •13.1.4Practical Learning: Using the Default Constructor
- •13.1.5The Constructor Initializer
- •Int main()
- •13.1.6Practical Learning: Initializing Using the Default Constructor
- •Int main()
- •Item Number: 0
- •13.1.7Constructor Overloading
- •Int main()
- •13.1.8Practical Learning: Overloading the Constructor
- •Inline long cStoreItem::GetItemNumber()
- •Inline void cStoreItem::SetItemNumber(const long number)
- •13.1.9Techniques of Initializing With a Constructor
- •Int main()
- •13.1.10Practical Learning: Initializing With the Constructors
- •13.2The Copy Constructor
- •13.2.1 Copying an Object
- •Int main()
- •13.2.2Using a Copy Constructor
- •13.3Destructors
- •13.3.1Introduction
- •13.3.2Practical Learning: Creating a Destructor
- •13.3.3Object Destruction in the Native Heap
- •13.3.4Object Destruction and the Managed Heap
- •14. The Properties of a Class
- •14.1Properties Fundamentals
- •14.1.1Introduction
- •14.1.2Practical Learning: Introducing the Properties of a Class
- •Int main()
- •14.1.3Reference Methods
- •Int main()
- •Int main()
- •14.1.4A Property
- •14.2Types of Properties
- •14.2.1 Simple Properties
- •Void ShowCharacteristics(cRectangle %recto)
- •Int main()
- •Int main()
- •14.2.2Practical Learning: Creating Simple Properties
- •Int main()
- •Item Number: 0
- •Item Number: 513497
- •14.2.3Read-Only Properties
- •Int main()
- •14.2.4Practical Learning: Using Read-Only Properties of a Class
- •Int main()
- •14.2.5Write-Only Properties
- •Void set(double h) { }
- •Int main()
- •14.2.6Read/Write Properties
- •14.2.7Practical Learning: Using Read/Write Properties of a Class
- •Int main()
- •Information");
- •Item Number: 666802
- •Item Number: 666802
- •14.3Other Techniques of Implementing Properties
- •14.3.1 Static Properties
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •15.1.2Declaring a Pointer to Function
- •Int main()
- •Void (*SomethingToSay)(void);
- •Void MovieQuote()
- •Void MovieQuote()
- •Int main()
- •Void (*SomethingToSay)();
- •15.1.3A Function Pointer that Returns a Value
- •Int Addition()
- •Int main()
- •Int (*SomeNumber)();
- •15.1.4A Function Pointer With Arguments
- •15.1.5Type-Defining a Function Pointer
- •Int Addition(int a, int b)
- •Int main()
- •15.1.6A Pointer to a Function as Argument
- •Int main()
- •15.2Classes and Pointers to Functions
- •15.2.1A Pointer to Function as a Member Variable
- •Int main()
- •Int main()
- •15.3Delegates
- •15.3.1 Introduction
- •15.3.2Practical Learning: Introducing Delegates
- •Void Show();
- •Void cFlower::Show()
- •Int main()
- •15.3.3Delegate Declaration
- •15.3.4Practical Learning: Creating a Delegate
- •Int main()
- •15.3.5Techniques of Using a Delegate
- •Int main()
- •Int main()
- •Int main()
- •Void ShowResult()
- •Int main()
- •15.3.6Practical Learning: Creating a Delegate
- •Int main()
- •15.3.7Delegates Compositions
- •15.3.8A Delegate With One of More Arguments
- •Void ShowResult()
- •Int main()
- •15.3.9Practical Learning: Using an Argumentative Delegate
- •Void Show(const int qty);
- •Void cFlower::Show(const int qty)
- •Int main()
- •15.3.10A Delegate Passed as Argument
- •Void CircleCharacteristics()
- •Int main()
- •16. Introduction to Conditions
- •16.1Boolean Variables
- •16.1.1 Introduction
- •16.1.2Practical Learning: Introducing Conditions
- •Int get() { return _tp; }
- •Int get() { return _clr; }
- •Int get() { return _qty; }
- •Int type, color, qty;
- •16.1.3Declaring a Boolean Variable
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •16.1.4Retrieving the Value of a Boolean Variable
- •Int main()
- •If Yes, enter True. Otherwise enter False: true
- •16.1.5Creating a Boolean Member Variable
- •16.1.6 Boolean Arguments
- •16.1.7A Boolean Property
- •16.1.8 Practical Learning: Creating a Boolean Property
- •16.2Enumerations
- •16.2.1 Introduction
- •Int main()
- •Int main()
- •16.2.2 Indexing the Members of an Enumeration
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •16.2.3Declaring an Enumeration Variable
- •16.2.4Global Enumerations
- •16.2.5Enumerations and Assemblies
- •16.3Enumerations and Classes
- •16.3.1 An Enumeration as a Member Variable
- •16.3.2An Enumeration as a Class
- •16.3.4Practical Learning: Creating Enumerations
- •17. Conditional Operators
- •18. Conditional Statements
- •19. Counting and Looping
- •20. Strings
- •21. Techniques on Using Inheritance
- •22. Variable Scope and Casting
- •23. Templates
- •24. Generics
- •25.Введение в массивы
- •25.1 Описание
- •25.1.1 Определение
- •25.1.2Создание массива
- •Int main()
- •Int Numbers[5];
- •25.1.3Initializing an Array
- •Int main()
- •Int main()
- •25.1.4 Type Defining an Array
- •Int main()
- •25.2Arrays and Memory Management
- •25.2.1 Creating a Dynamic Array
- •Int main()
- •Int main()
- •25.2.2 Cleaning After an Array
- •Int main()
- •25.3Managed Arrays
- •25.3.1 Introduction
- •Int main()
- •Int main()
- •25.3.2Practical Learning: Introducing Arrays
- •Int main()
- •25.3.3An Array of Handles
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •Int main()
- •25.3.4Practical Learning: Using an Array of Handles
- •Int main()
- •25.4Arrays and Functions
- •25.4.1 Returning an Array
- •Int main()
- •25.4.2Practical Learning: Returning Arrays
- •25.4.3Passing an Array as Argument
- •25.4.4Practical Learning: Passing an Array as Argument
- •26. Multi-Dimensional Arrays
- •26.1 Single and Two-Dimensional Arrays
- •26.1.1 Introduction
- •26.1.2Practical Learning: Introducing Multi-Dimensional Arrays
- •26.1.4Multi-Dimensional Arrays
- •26.2Introduction to Jagged Arrays
- •26.2.1 Introduction
- •26.2.2 Creating a Jagged Array
- •26.2.3 Initializing a Jagged Array
- •26.3Jagged Arrays and Functions
- •26.3.1Returning a Jagged Array
- •26.3.2Passing a Jagged Array as Argument
- •26.4Multi-Dimensional Jagged Arrays
- •26.4.1Two-Dimensional Jagged Arrays
- •26.4.2Multi-Dimensional Jagged Arrays
- •27.Arrays and Classes
- •27.1The Array Class
- •27.1.1 Introduction
- •27.1.2 The Length of an Array
- •Int main()
- •28.Introduction to File Processing
- •29.Details on File Processing
- •30.Files Operations
- •31.Serialization
- •32.Introduction to Indexed Properties
- •33.Classes and Indexed Properties
- •34.Введение в коллекции
- •34.1Коллекции на основе массива
- •34.1.1Вступление
- •34.1.2Объявление коллекции
- •Int main()
- •34.1.3 Количество элементов в коллекции
- •34.2Операции над коллекцией, основанной на массиве
- •34.2.1 Добавление элемента
- •Int size;
- •Int get() { return size; }
- •Int main()
- •34.2.2 Извлечение элемента из коллекции
- •Int size;
- •Int get() { return size; }
- •Int main()
- •34.2.3 Вставка элемента в коллекцию
- •Int size;
- •Int get() { return size; }
- •1. Список не заполнен до конца
- •2. Указанная позиция находится в допустимом диапазоне
- •Int main()
- •34.2.4 Удаление элемента из коллекции
- •Int size;
- •Int get() { return size; }
- •Int main()
- •34.3Коллекция элементов (заказ букета цветов)
- •34.3.1 Вступление
- •34.3.2Practical Learning: Introducing Collections
- •34.3.3 Implementing a Collection
- •34.3.4 Practical Learning: Creating a cCollection Class
- •34.3.5The Beginning of a Collection
- •34.3.6 Linking the Items of a Collection
- •34.3.7 Practical Learning: Creating a List's Monitor
- •34.4 Коллекции на основе списка (Operations on a Collection)
- •34.4.1 Adding an Item
- •34.4.2 Practical Learning: Adding Items to a Collection
- •34.4.3Retrieving an Item
- •34.4.4 Practical Learning: Retrieving the Items of a Collection
- •34.4.5 Removing an Item
- •34.4.6 Practical Learning: Retrieving the Items of a Collection
- •34.4.7 Locating an Item
- •35.Основы коллекций платформы .Net (Fundamentals of .Net Support For Collections)
- •35.1 Перечисление элементов коллекции (Enumerating the Members of a Collection)
- •35.1.1 Введение в коллекции System
- •35.1.2Практический пример
- •Int Mileage;
- •Int items;
- •Int get() { return items; }
- •Virtual bool Delete() override;
- •Items--;
- •35.1.3Introduction to the iEnumerator Interface
- •35.1.4 Упражнение
- •35.1.5 Текущий элемент перечисления
- •35.1.6Упражнение
- •Int curPosition;
- •35.1.7Сброс метки текущего элемента
- •Void Reset();
- •Virtual void Reset();
- •Void cEnumerator::Reset()
- •35.1.8 Упражнение
- •Int curPosition;
- •Virtual void Reset();
- •Void cCarIdentifier::Reset()
- •35.1.9Перемещение к следующему элементу в iEnumerator
- •Virtual void Reset();
- •Virtual bool MoveNext();
- •Void cEnumerator::Reset()
- •35.1.10Упражнение
- •Int curPosition;
- •Virtual void Reset();
- •Virtual bool MoveNext();
- •Void cCarIdentifier::Reset()
- •35.2Перечислимая коллекция (An Enumerable Collection)
- •35.2.1 Вступление
- •35.2.2 Получение Enumerator (Getting the Enumerator)
- •35.2.3Упражнение
- •36.Встроенные интерфейсы коллекций
- •36.1 Обзор интерфейсов коллекций
- •36.1.1 Вступление
- •36.1.2Choosing a Class or an Interface
- •36.2Интерфейс iCollection
- •36.2.1 Вступление
- •36.2.2Реализация iCollection
- •Int nbrOfStudents;
- •Virtual property int Count
- •Int get() { return nbrOfStudents; }
- •Int nbrOfItems;
- •Virtual property int Count
- •Int get() { return nbrOfItems; }
- •Int nbrOfItems;
- •Int nbrOfItems;
- •Virtual property bool IsSynchronized
- •Int nbrOfItems;
- •36.3Интерфейс iList
- •36.3.1Вступление
- •36.3.2Упражнение
- •Int main()
- •36.3.3Implementing iList
- •36.3.4 Упражнение
- •36.4Размер коллекции
- •36.4.1 Коллекция фиксированного размера
- •Int items;
- •Virtual property bool IsFixedSize
- •36.4.2 Упражнение
- •Int counter;
- •Virtual property bool IsFixedSize
- •36.4.3Коллекция только для чтения
- •36.4.4Упражнение
- •Int counter;
- •Virtual void RemoveAt(int index);
- •Virtual void Clear(void);
- •36.5Наполнение коллекции
- •36.5.1 Добавление элементов
- •Int items;
- •36.5.2Упражнение
- •Int main()
- •36.5.3Вставка элемента
- •36.5.4Упражнение
- •Int main()
- •36.6Размещение элемента в коллекции
- •36.6.1 Значение по умолчанию в коллекции
- •Int items;
- •36.6.2Упражнение
- •Int counter;
- •Int main()
- •36.6.3Проверка существования элемента в коллекции
- •Int items;
- •36.6.4 Упражнение: проверка наличия элемента в коллекции
- •Int main()
- •36.6.5Получение индекса элемента
- •Int items;
- •36.6.6Упражнение: получение индекса элемента
- •Int main()
- •36.7Удаление элементов коллекции
- •36.7.1 Удаление элемента по его индексу
- •37.Встроенные классы коллекций
- •37.1 Класс ArrayList
- •37.1.1 Вступление
- •37.1.2 Емкость списка (The Capacity of a List)
- •37.1.3Список только для чтения
- •37.1.4Добавление элементов
- •37.1.5 Число элементов в списке
- •37.1.6 Получение элементов списка
- •37.1.7Доступ к элементу списка
- •37.1.8Удаление элемента
- •37.2Хеш-таблицы
- •37.2.1Вступление
- •37.2.2Создание хеш-таблицы
- •37.2.3Доступ к элементам хеш-таблицы
- •If (!diGcs.Exists)
- •If (!File.Exists(strFilename))
- •If (!File.Exists(strFilename))
- •If (File.Exists(strFilename))
- •If (File.Exists(strFilename))
- •If (File.Exists(strFilename))
- •37.2.4Доступ к элементу хеш-таблицы
- •37.2.5Удаление элементов хеш-таблицы
- •37.3Стек
- •37.3.1 Вступление
- •37.3.2Создание стека
- •37.3.3Добавление элементов в стек
- •37.3.4Доступ к элементам стека
- •37.3.5Удаление элементов из стека
- •37.4Очередь
- •37.4.1Вступление
- •37.4.2Создание очереди
- •37.4.3Построение очереди (Building a Queue)
- •37.4.4Получение элементов очереди
- •37.4.5Удаление элементов из очереди
27.1The Array Class
27.1.1 Introduction
Для того чтобы облегчить создание и использование массивов, .NET Framework предоставляет класс Array. Этот класс содержит различные свойства и методы, позволяющие выполнять почти все виды операций, необходимые для решения практических задач. Другой аспект .NET Framework состоит в том, что всякий раз, когда вы создаете управляемый массив, он фактически наследует свойства и методы класса Array.
27.1.2 The Length of an Array
We saw that, when declaring an array, you must specify the number of elements that the array variable contains. This number is also referred to as the length of the array. The Array class represents this number with the Length property. This property is read-only, meaning you can only retrieve its value, you cannot change it. Based on this, to find out the number of elements in an array, retrieve the value of its Length property. Here is an example:
using namespace System;
Int main()
{
array<double> ^ Numbers = gcnew array<double>(5);
Numbers[0] = 1;
Numbers[1] = 2;
Numbers[2] = 3;
Numbers[3] = 4;
Numbers[4] = 5;
Console::WriteLine(L"The array contains {0} elements\n",
Numbers->Length); // 5
return 0;
}
28.Introduction to File Processing
|
Overview of File Processing and Definitions |
|
Introduction |
|
In Lesson 3, we saw that a piece of information used in an application was primarily represented as a group of bits. So far, if we requested information from the user, when the application exited, we lost all information that the user had entered. This is because such information was only temporarily stored in the random access memory (RAM). In some cases, you will want to "keep" information that the user has entered so you can make the information available the next time the user opens the application. In some other cases, whether you request information from the user or inherently provide it to the user, you may want different people working from different computers to use or share the same data. In these and other scenarios, you must store the information somewhere and retrieve it when necessary. This is the basis of file processing.
Files |
|
A file is a series of bytes of data that are arranged in a particular manner to produce a usable document. For easy storage, location, and management, the bytes are stored on a medium such as a hard disc, a floppy disc, a compact disc, or any valid and supported type of storage. When these bytes belong to a single but common entity and hold values that are stored on a medium, the group is referred to as a file.
For greater management, files can be stored in a parent object called a directory or a folder. Since a file is a unit of storage and it stores information, it has a size, which is the number of bits it uses to store its values. To manage it, a file has a location also called a path that specifies where and/or how the file can be retrieved. Also, for better management, a file has attributes (characteristics) that indicate what can be done on the file or that provide specific information that the programmer or the operating system can use when dealing with the file.
Streams |
|
File processing consists of creating, storing, and/or retrieving the contents of a file from a recognizable medium. For example, it is used to save word-processed files to a hard drive, to store a presentation on floppy disk, or to open a file from a CD-ROM. A stream is the technique or means of performing file processing. In order to manage files stored in a computer, each file must be able to provide basic pieces of information about itself. This basic information is specified when the file is created but can change during the lifetime of a file.
To create a file, a user must first decide where it would be located: this is a requirement. A file can be located on the root drive. Alternatively, a file can be positioned inside of an existing folder. Based on security settings, a user may not be able to create a file just anywhere in the (file system of the) computer. Once the user has decided where the file would reside, there are various means of creating files that the users are trained to use. When creating a file, the user must give it a name following the rules of the operating system combined with those of the file system. The most fundamental piece of information a file must have is a name.
Once the user has created a file, whether the file is empty or not, the operating system assigns basic pieces of information to it. Once a file is created, it can be opened, updated, modified, renamed, etc.
Streaming Prerequisites |
|
Introduction |
|
To support file processing, the .NET Framework provides the System::IO namespace that contains many different classes to handle almost any type of file operation you may need to perform. Therefore, to perform file processing, you can include the System::IO namespace in your project.
The parent class of file processing is Stream. With Stream, you can store data to a stream or you can retrieve data from a stream. Stream is an abstract class, which means that you cannot use it to declare a variable in your application. As an abstract class, Stream is used as the parent of the classes that actually implement the necessary operations. You will usually use a combination of classes to perform a typical operation. For example, some classes are used to create a stream object while some others are used to write data to the created stream.
Practical Learning: Introducing Streaming |
|
Start Microsoft Visual C++ and create a new CLR Console Application named IceCream3
Change the file as follows:
// IceCream3.cpp : main project file.
#include "stdafx.h"
using namespace System;
// This class is used to create and manage an ice scream
// and to process an order
public ref class CIceCream sealed
{
public:
// This is the base price of an ice scream
// Optional values may be added to it
static const double BasePrice = 1.55;
// These arrays are used to build the components
// of various ice screams
private:
array<String ^> ^ Flavor;
array<String ^> ^ Container;
array<String ^> ^ Ingredient;
// Additional factor used to process an ice scream order
int Scoops;
double TotalPrice;
// Variables that will hold the user's choice
// These are declared "globally" so they can be
// shared among methods
int ChoiceFlavor;
int ChoiceContainer;
int ChoiceIngredient;
// This default constructor is the best place for
// us to initialize the array
public:
CIceCream()
{
Flavor = gcnew array<String ^>(10);
Flavor[0] = L"Vanilla";
Flavor[1] = L"Cream of Cocoa";
Flavor[2] = L"Chocolate Chip";
Flavor[3] = L"Organic Strawberry";
Flavor[4] = L"Butter Pecan";
Flavor[5] = L"Cherry Coke";
Flavor[6] = L"Chocolate Brownies";
Flavor[7] = L"Caramel Au Lait";
Flavor[8] = L"Chunky Butter";
Flavor[9] = L"Chocolate Cookie";
Ingredient = gcnew array<String^>(4);
Ingredient[0] = L"No Ingredient";
Ingredient[1] = L"Peanuts";
Ingredient[2] = L"M & M";
Ingredient[3] = L"Cookies";
Container = gcnew array<String^>(3);
Container[0] = L"Cone";
Container[1] = L"Cup";
Container[2] = L"Bowl";
}
// This method requests a flavor from the user and
// returns the choice
void ChooseFlavor()
{
// Make sure the user selects a valid number
//that represents a flavor...
do {
// In case the user types a symbol that
// is not a number
try {
Console::WriteLine(L"What type of flavor do you want?");
for (int i = 0; i < Flavor->Length; i++)
Console::WriteLine(L"{0} - {1}", i + 1, Flavor[i]);
Console::Write(L"Your Choice? ");
ChoiceFlavor = int::Parse(Console::ReadLine());
}
catch(FormatException ^) // display an appropriate message
{
Console::WriteLine(L"You must enter a valid number "
L"and no other character!");
}
// If the user typed an invalid number out of the
// allowed range
// let him or her know and provide another chance
if( ChoiceFlavor < 1 || ChoiceFlavor > Flavor->Length)
Console::WriteLine(L"Invalid Choice - Try Again!\n");
} while (ChoiceFlavor < 1 || ChoiceFlavor > Flavor->Length);
}
// This method allows the user to select a container
void ChooseContainer()
{
// Make sure the user selects a valid number that
// represents a container
do {
// If the user types a symbol that is not a number
try
{
Console::WriteLine(L"What type of container do you want?");
for (int i = 0; i < Container->Length; i++)
Console::WriteLine(L"{0} - {1}", i + 1, Container[i]);
Console::Write(L"Your Choice? ");
ChoiceContainer = int::Parse(Console::ReadLine());
}
catch (FormatException ^) // display an appropriate message
{
Console::WriteLine(L"You must enter a valid "
L"number and no other character!");
}
// If the user typed an invalid number out of the
// allowed range
// let him or her know and provide another chance
if( (ChoiceContainer < 1) ||
(ChoiceContainer > Container->Length) )
Console::WriteLine(L"Invalid Choice - Try Again!");
} while ((ChoiceContainer < 1) ||
(ChoiceContainer > Container->Length));
}
void ChooseIngredient()
{
do {
try {
Console::WriteLine(L"Do you want an ingredient or not");
for (int i = 0; i < Ingredient->Length; i++)
Console::WriteLine(L"{0} - {1}",
i + 1, Ingredient[i]);
Console::Write(L"Your Choice? ");
ChoiceIngredient = int::Parse(Console::ReadLine());
}
catch (FormatException ^)
{
Console::WriteLine(L"You must enter a valid "
L"number and no other character!");
}
if( (ChoiceIngredient < 1) ||
(ChoiceIngredient > Ingredient->Length) )
Console::WriteLine(L"Invalid Choice - Try Again!");
} while ((ChoiceIngredient < 1) ||
(ChoiceIngredient > Ingredient->Length));
}
void SpecifyNumberOfScoops()
{
do {
try {
Console::Write(L"How many scoops(1, 2, or 3)? ");
Scoops = int::Parse(Console::ReadLine());
}
catch (FormatException ^)
{
Console::WriteLine(L"You must enter a valid number "
L"and no other character!");
}
if( Scoops < 1 || Scoops > 3 )
Console::WriteLine(L"Invalid Choice - Try Again!");
} while (Scoops < 1 || Scoops > 3);
}
// This method is used to process a customer order
// It uses the values of the above methods
void ProcessAnOrder()
{
double PriceIngredient, PriceScoop;
// Let the user know that this is a vending machine
Console::WriteLine(L"=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
Console::WriteLine(L"Ice Scream Vending Machine");
Console::WriteLine(L"-----------------------------------");
// Let the user select the components of the ice scream
ChooseFlavor();
Console::WriteLine(L"-----------------------------------");
ChooseContainer();
Console::WriteLine(L"-----------------------------------");
ChooseIngredient();
Console::WriteLine(L"-----------------------------------");
SpecifyNumberOfScoops();
Console::WriteLine(L"-----------------------------------");
// If the user selects an ingredient instead of "No Ingredient",
// add $0.50 to the order
if( (ChoiceIngredient == 2) ||
(ChoiceIngredient == 3) ||
(ChoiceIngredient == 4) )
PriceIngredient = 0.50;
else
PriceIngredient = 0.00;
// Instead of multiplying a number scoops to a value,
// We will use an incremental value depending on
// the number of scoops
if( Scoops == 1 )
PriceScoop = 0.65;
else if( Scoops == 2 )
PriceScoop = 1.05;
else
PriceScoop = 1.55;
// Calculate the total price of the ice scream
TotalPrice = BasePrice + PriceScoop + PriceIngredient;
// Create the ice scream...
// And display a receipt to the user
DisplayReceipt();
}
// This method is used to display a receipt to the user
void DisplayReceipt()
{
Console::WriteLine(L"\n=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
Console::WriteLine(L"Ice Scream Order");
Console::WriteLine(L"-----------------------------------");
Console::WriteLine(L"Flavor: {0}",
Flavor[ChoiceFlavor - 1]);
Console::WriteLine(L"Container: {0}",
Container[ChoiceContainer - 1]);
Console::WriteLine(L"Ingredient: {0}",
Ingredient[ChoiceIngredient - 1]);
Console::WriteLine(L"Scoops: {0}", Scoops);
Console::WriteLine(L"Total Price: {0:C}", TotalPrice);
Console::WriteLine(L"=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=\n");
}
};
int main(array<System::String ^> ^args)
{
CIceCream ^ ic = gcnew CIceCream();
ic->ProcessAnOrder();
Console::WriteLine();
return 0;
}
Execute the project and test it. Here is an example:
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Ice Scream Vending Machine
-----------------------------------
What type of flavor do you want?
1 - Vanilla
2 - Cream of Cocoa
3 - Chocolate Chip
4 - Organic Strawberry
5 - Butter Pecan
6 - Cherry Coke
7 - Chocolate Brownies
8 - Caramel Au Lait
9 - Chunky Butter
10 - Chocolate Cookie
Your Choice? 3
-----------------------------------
What type of container do you want?
1 - Cone
2 - Cup
3 - Bowl
Your Choice? 5
Invalid Choice - Try Again!
What type of container do you want?
1 - Cone
2 - Cup
3 - Bowl
Your Choice? 3
-----------------------------------
Do you want an ingredient or not
1 - No Ingredient
2 - Peanuts
3 - M & M
4 - Cookies
Your Choice? 8
Invalid Choice - Try Again!
Do you want an ingredient or not
1 - No Ingredient
2 - Peanuts
3 - M & M
4 - Cookies
Your Choice? 4
-----------------------------------
How many scoops(1, 2, or 3)? 3
-----------------------------------
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Ice Scream Order
-----------------------------------
Flavor: Chocolate Chip
Container: Bowl
Ingredient: Cookies
Scoops: 3
Total Price: $3.60
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Press any key to continue . . .
Close the DOS window
The Name of a File |
|
Before performing file processing, one of your early decisions will consist of specifying the type of operation you want the user to perform. For example, the user may want to create a brand new file, open an existing file, or perform a routine operation on a file. In all or most cases, whether you are creating a new file or manipulating an existing one, you must specify the name of the file. You can do this by declaring a String variable but, as we will learn later on, most classes used to create a stream can take a string that represents the file.
If you are creating a new file, there are certainly some rules you must observe. The name of a file follows the directives of the operating system. On MS DOS and Windows 3.X (that is, prior to Microsoft Windows 9X), the file had to use the 8.3 format. The actual name had to have a maximum of 8 characters with restrictions on the characters that could be used. The user also had to specify three characters after a period. The three characters, known as the file extension, were used by the operating system to classify the file. That was all necessary for those 8-bit and 16-bit operating systems. Various rules have changed. For example, the names of folders and files on Microsoft Windows >= 95 can have up to 255 characters. The extension of the file is mostly left to the judgment of the programmer but the files are still using extensions. Applications can also be configured to save different types of files; that is, files with different extensions.
|
At the time of this writing, the rules for file names for Microsoft Windows were on the MSDN web site at Windows Development\Windows Base Services\Files and I/O\SDK Documentation\Storage\Storage Overview\File Management\Creating, Deleting, and Maintaining Files\Naming a File (because it is a web site and not a book, its pages can change anytime). |
Based on this, if you declare a string variable to hold the name of the file, you can simply initialize the variable with the necessary name and its extension. Here is an example:
using namespace System;
int main()
{
String ^ NameOfFile = L"Employees.spr";
return 0;
}
Practical Learning: Specifying the Name of a File |
|
Access the IceCream.cs file and add a new public method named SaveOrder of type void as follows:
// IceCream3.cpp : main project file.
#include "stdafx.h"
using namespace System;
// This class is used to create and manage an ice scream
// and to process an order
public ref class CIceCream sealed
{
. . . No Change
// This method is used to display a receipt to the user
void DisplayReceipt()
{
. . . No Change
}
void SaveOrder()
{
String ^ NameOfFile;
Console::Write(L"Please enter your initials or the "
L"name we will use to remember your order: ");
NameOfFile = Console::ReadLine();
}
};
int main(array<System::String ^> ^args)
{
char answer = L'n';
CIceCream ^ ic = gcnew CIceCream();
ic->ProcessAnOrder();
Console::Write(L"Do you want us to remember this "
L"order the next time you come to "
L"get your ice scream (y/n)? ");
answer = char::Parse(Console::ReadLine());
if( answer == L'y' || answer == L'Y' )
ic->SaveOrder();
Console::WriteLine();
return 0;
}
Execute the project and test it
Close the DOS window
The Path to a File |
|
If you declare a string as above, the file will be created in the folder as the application. Otherwise, you can create your new file anywhere in the hard drive or on another medium. To do that, you must provide a complete path where the file will reside. A path is a string that specifies the drive (such as A:, C:, or D:, etc). The sections of a complete path are separated by a backslash. For example, a path can be made of a folder followed by the name of the file. An example would be
C:\Palermo.tde
A path can also consist of a drive followed by the name of the folder in which the file will be created. Here is an example:
C:\Program Files\Palermo.tde
A path can also indicate that the file will be created in a folder that itself is inside of another folder. In this case, remember that the names of folders must be separated by backslashes.
In Lesson 2, we saw that the backslash character is used to create or manage escape sequences and it can be included in a string value to make up an escape sequence. Because of this, every time you include a backslash in a string, the compiler thinks that you are trying to provide an escape sequence. In this case, if the combination of the backslash and the character that follows the backslash is not recognized as an escape sequence, you would get an error. To solve this problem, you have two alternatives. To indicate that the backslash must be considered as a character in its own right, you can double it. Here are examples:
int main()
{
String ^ NameOfFile = L"C:\\Documents and "
L"Settings\\Business Records\\Employees.spr";
return 0;
}
}
In the same way, you can declare a String variable to represent the name of an existing file that you plan to use in your program. You can also represent its path.
When providing a path to the file, if the drive you specify doesn't exist or cannot be read, the compiler would consider that the file doesn't exist. If you provide folders that don't exist in the drive, the compiler would consider that the file doesn't exist. This also means that the compiler will not create the folder(s) (the .NET Framework provides all means to create a folder but you must ask the compiler to create it; simply specifying a folder that doesn't exist will not automatically create it, even if you are creating a new file). Therefore, it is your responsibility to make sure that either the file or the path to the file is valid. As we will see in the next section, the compiler can check the existence of a file or path.
The .NET Support for Files |
|
Introduction |
|
The primary support of a file as an object is provided by a .NET Framework class called File. This static class is equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file.
File Existence |
|
One of the valuable operations that the File class can perform is to check the existence of the file you want to use. For example, if you are creating a new file, you may want to make sure it doesn't exist already because if you try to create a file that exists already, the compiler may first delete the old file before creating the new one. This could lead to unpredictable result, especially because such a file is not sent to the Recycle Bin. On the other hand, if you are trying to open a file, you should first make sure the file exists, otherwise the compiler will not be able to open a file it cannot find.
To check the existence of a file, the File class provides the Exists method. Its syntax is:
public:
static bool Exists(String ^path);
If you provide only the name of the file, the compiler would check it in the folder of the application. If you provide the path to the file, the compiler would check its drive, its folder(s) and the file itself. In both cases, if the file exists, the method returns true. If the compiler cannot find the file, the method returns false. It's important to know that if you provided a complete path to the file, any slight mistake would produce a false result.
Practical Learning: Checking the Existence of a File |
|
Access the IceCream.cs file and change it as follows:
// IceCream3.cpp : main project file.
#include "stdafx.h"
using namespace System;
using namespace System::IO;
// This class is used to create and manage an ice scream
// and to process an order
public ref class CIceCream sealed
{
public:
. . . No Change
// This method is used to display a receipt to the user
void DisplayReceipt()
{
. . . No Change
}
void SaveOrder()
{
String ^ NameOfFile;
Console::Write(L"Please enter your initials or the "
L"name we will use to remember your order: ");
NameOfFile = Console::ReadLine();
if( File::Exists(NameOfFile) )
{
char Answer;
Console::WriteLine(L"The file you entered exists already.");
Console::Write(L"Do you want to replace it(y/n)?" );
Answer = char::Parse(Console::ReadLine());
if( Answer == L'y' || Answer == L'Y' )
Console::WriteLine(L"The former order with the "
L"same name will be replaced");
else if( Answer == L'n' || Answer == L'N' )
{
Console::WriteLine(L"Please enter a name we will "
L"use to remember this order: ");
NameOfFile = Console::ReadLine();
}
else
Console::WriteLine(L"Invalid Answer - We will close");
return;
}
else
Console::WriteLine(L"Great");
}
void OpenOrder()
{
String ^ NameOfFile;
Console::Write(L"Please enter the name you previously "
L"gave to remember your order: ");
NameOfFile = Console::ReadLine();
if( File::Exists(NameOfFile) )
Console::WriteLine(L"The file would have been opened");
else
Console::WriteLine(L"The name you entered is not registered "
L"in our previous orders");
}
};
int main(array<System::String ^> ^args)
{
char answer = L'n';
CIceCream ^ ic = gcnew CIceCream();
ic->ProcessAnOrder();
Console::Write(L"Do you want us to remember this "
L"order the next time you come to "
L"get your ice scream (y/n)? ");
answer = char::Parse(Console::ReadLine());
if( answer == L'y' || answer == L'Y' )
ic->SaveOrder();
else
Console::WriteLine(L"It was nice serving you."
L"\nCome Again!!!\n");
Console::WriteLine();
return 0;
}
Execute it
File Creation |
|
Besides checking the existence of the file, the File class can be used to create a new file. To support this operation, the File class is equipped with the Create() method that is overloaded with two versions as follows:
public:
static FileStream ^ Create(String ^ path);
public:
static FileStream ^ Create(String ^ path, int buffersize);
In both cases, the File.Create() method returns a Stream value, in this case a FileStream value. As the File.Create() method indicates, it takes the name or path of the file as argument. If you know or want to specify the size, in bytes, of the file, you can use the second version.
To provide the same operation of creating a file, you can use the Open() method of the File class. It is overloaded in three versions as follows:
public:
static FileStream ^ Open(String ^ path, FileMode mode);
public:
static FileStream ^ Open(String ^ path,
FileMode mode,
FileAccess access);
public:
static FileStream Open(String ^ path,
FileMode mode,
FileAccess access,
FileShare share);
Access to a File |
|
In order to perform an operation on a file, you must specify to the operating system how to proceed. One of the options you have is to indicate the type of access that will be granted on the file. This access is specified using the FileAccess enumerator. The members of the FileAccess enumerator are:
FileAccess::Write: New data can be written to the file
FileAccess.Read: Existing data can be read from the file
FileAccess.ReadWrite: Existing data can be read from the file and new data be written to the file
File Sharing |
|
In standalone workstations, one person is usually able to access and open a file then perform the necessary operations on it. In networked computers, you may create a file that different people can access at the same time or you may make one file access another file to retrieve information. For example, suppose you create an application for a fast food restaurant that has two or more connected workstations and all workstations save their customers orders to a common file. In this case, you must make sure that any of the computers can access the file to save an order. An employee from one of these workstations must also be able to open the file to retrieve a customer order for any necessary reason. You can also create a situation where one file holds an inventory of the items of a store and another file holds the customers orders. Obviously one file would depend on another. Based on this, when an operation must be performed on a file, you may have to specify how a file can be shared. This is done through the FileShare enumerator.
The values of the FileShare enumerator are:
FileShare.Inheritable: Allows other file handles to inherit from this file
FileShare.None: The file cannot be shared
FileShare.Read: The file can be opened and read from
FileShare::Write: The file can be opened and written to
FileShare.ReadWrite: The file can be opened to write to it or read from it
The Mode of a File |
|
Besides the access to the file, another option you will most likely specify to the operating system is referred to as the mode of a file. It is specified through the FileMode enumerator. The members of the FileMode Enumerator are:
FileMode.Append: If the file already exists, the new data will be added to its end. If the file doesn't exist, it will be created and the new data will be added to it
FileMode.Create: If the file already exists, it will be deleted and a new file with the same name will be created. If the file doesn't exist, then it will be created
FileMode.CreateNew: If the new already exists, the compiler will throw an error. If the file doesn't exist, it will be created
FileMode.Open: If the file exists, it will be opened. If the file doesn't exist, an error would be thrown
FileMode.OpenOrCreate: If the file already exists, it will be opened. If the file doesn't exist, it will be created
FileMode.Truncate: If the file already exists, its contents will be deleted completely but the file will be kept, allowing you to write new data to it. If the file doesn't exist, an error would be thrown
Fundamentals of File Streaming |
|
Introduction |
|
File streaming consists of performing one of the routine operations on a file, such as creating it or opening it. This basic operation can be performed using a class called FileStream. You can use a FileStream object to get a stream ready for processing. As one of the most complete classes of file processing of the .NET Framework, FileStream is equipped with all necessary properties and methods. To use it, you must first declare a variable of it. The class is equipped with nine constructors.
One of the constructors (the second) of the FileStream class has the following syntax:
public:
FileStream(String ^ path, FileMode mode);
This constructor takes as its first argument the name or the file or its path. The second argument specifies the type of operation to perform on the file. Here is an example:
using namespace System;
using namespace System::IO;
int main()
{
String ^ NameOfFile = L"Persons.spr";
FileStream ^ fstPersons = gcnew FileStream(NameOfFile,
FileMode::Create);
return 0;
}
Practical Learning: Creating a Stream |
|
To create a new stream, change the SaveOrder() method in the IceCream.cs file and as follows:
// IceCream3.cpp : main project file.
#include "stdafx.h"
using namespace System;
using namespace System::IO;
// This class is used to create and manage an ice scream
// and to process an order
public ref class CIceCream sealed
{
. . . No Change
void SaveOrder()
{
String ^ NameOfFile;
FileStream ^ stmIceCream =
gcnew FileStream(NameOfFile, FileMode::Create);
. . . No Change
}
void OpenOrder()
{
. . . No Change
}
};
int main(array<System::String ^> ^args)
{
. . . No Change
Console::WriteLine();
return 0;
}
Save the file
Stream Writing |
|
A streaming operation is typically used to create a stream. Once the stream is ready, you can write data to it. The writing operation is perform through various classes. One of these classes is BinaryWriter.
The BinaryWriter class can be used to write values of primitive data types (char, int, float, double, etc). To use a BinaryWriter value, you can first declare its variable. To do this, you would use one of the class' three constructors. One of its constructors (the second) has the following syntax:
public:
BinaryWriter(Stream ^ output);
This constructor takes as argument a Stream value, which could be a FileStream variable. Here is an example:
using namespace System;
using namespace System::IO;
int main()
{
String ^ NameOfFile = L"Persons.spr";
FileStream ^ fstPersons = gcnew FileStream(NameOfFile,
FileMode::Create);
BinaryWriter ^ wrtPersons = gcnew BinaryWriter(fstPersons);
return 0;
}
Most classes that are used to add values to a stream are equipped with a method called Write. This is also the case for the BinaryWriter class. This method takes as argument the value that must be written to the stream. The method is overloaded so that there is a version for each primitive data type. Here is an example that adds strings to a newly created file:
using namespace System;
using namespace System::IO;
int main()
{
String ^ NameOfFile = L"Persons.spr";
FileStream ^ fstPersons = gcnew FileStream(NameOfFile,
FileMode::Create);
BinaryWriter ^ wrtPersons = gcnew BinaryWriter(fstPersons);
wrtPersons->Write(L"James Bloch");
wrtPersons->Write(L"Catherina Wallace");
wrtPersons->Write(L"Bruce Lamont");
wrtPersons->Write(L"Douglas Truth");
return 0;
}
Stream Closing |
|
When you use a stream, it requests resources from the operating system and uses them while the stream is available. When you are not using the stream anymore, you should free the resources and make them available again to the operating system so that other services can use them. This is done by closing the stream.
To close a stream, you can can call the Close() method of the class(es) you were using. Here are examples:
using namespace System;
using namespace System::IO;
int main()
{
String ^ NameOfFile = L"Persons.spr";
FileStream ^ fstPersons = gcnew FileStream(NameOfFile,
FileMode::Create);
BinaryWriter ^ wrtPersons = gcnew BinaryWriter(fstPersons);
wrtPersons->Write(L"James Bloch");
wrtPersons->Write(L"Catherina Wallace");
wrtPersons->Write(L"Bruce Lamont");
wrtPersons->Write(L"Douglas Truth");
wrtPersons->Close();
fstPersons->Close();
return 0;
}
Practical Learning: Writing to a Stream |
|
To be able to complete a file, change the SaveOrder() method in the IceCream.cs file as follows:
// IceCream3.cpp : main project file.
#include "stdafx.h"
using namespace System;
using namespace System::IO;
// This class is used to create and manage an ice scream
// and to process an order
public ref class CIceCream sealed
{
public:
. . . No Change
void SaveOrder()
{
String ^ strNameOfFile;
Console::Write(L"Please enter your initials or the name "
L"we will use to remember your order: ");
strNameOfFile = Console::ReadLine();
strNameOfFile = strNameOfFile + L".icr";
// Find out if the user entered a name of a file
// that is already in the machine
if( File::Exists(strNameOfFile) )
{
char answer;
FileStream ^ stmIceCream =
gcnew FileStream(strNameOfFile, FileMode::Create);
BinaryWriter ^ bnwIceCream =
gcnew BinaryWriter(stmIceCream);
// If so, find out if the user wants to
// replace the old file
Console::WriteLine(L"The file you entered exists already.");
Console::Write(L"Do you want to replace it(y/n)?");
answer = char::Parse(Console::ReadLine());
// If the customer wants to replace it...
if( (answer == L'y') || (answer == 'Y') )
{
// ... do so
Console::WriteLine(L"The former order with the same "
L"name will be replaced");
Console::WriteLine(L"\n=-= Ice Scream Vending Machine =-=");
Console::WriteLine(L" Saving Order: {0}", strNameOfFile);
bnwIceCream->Write(Flavor[ChoiceFlavor - 1]);
bnwIceCream->Write(Container[ChoiceContainer - 1]);
bnwIceCream->Write(Ingredient[ChoiceIngredient - 1]);
bnwIceCream->Write(Scoops);
bnwIceCream->Write(TotalPrice);
}
// If the customer wants to save the new order with
// a different name
else if( (answer == L'n') || (answer == 'N') )
{
// Ask the user to enter a name to remember the order
Console::Write(L"Please enter a name we will use "
L"to remember this order: ");
strNameOfFile = Console::ReadLine();
strNameOfFile = strNameOfFile + L".icr";
stmIceCream = gcnew FileStream(strNameOfFile, FileMode::Create);
bnwIceCream = gcnew BinaryWriter(stmIceCream);
Console::WriteLine(L"\n=-= Ice Scream Vending Machine =-=");
Console::WriteLine(L" Saving Order: {0}", strNameOfFile);
bnwIceCream->Write(Flavor[ChoiceFlavor - 1]);
bnwIceCream->Write(Container[ChoiceContainer - 1]);
bnwIceCream->Write(Ingredient[ChoiceIngredient - 1]);
bnwIceCream->Write(Scoops);
bnwIceCream->Write(TotalPrice);
}
else
Console::WriteLine(L"Invalid Answer - We will close");
bnwIceCream->Close();
stmIceCream->Close();
}
else
{
FileStream ^ stmIceCream =
gcnew FileStream(strNameOfFile, FileMode::Create);
BinaryWriter ^ bnwIceCream =
gcnew BinaryWriter(stmIceCream);
Console::WriteLine(L"\n=-= Ice Scream Vending Machine =-=");
Console::WriteLine(L" Saving Order: {0}", strNameOfFile);
bnwIceCream->Write(Flavor[ChoiceFlavor - 1]);
bnwIceCream->Write(Container[ChoiceContainer - 1]);
bnwIceCream->Write(Ingredient[ChoiceIngredient - 1]);
bnwIceCream->Write(Scoops);
bnwIceCream->Write(TotalPrice);
bnwIceCream->Close();
stmIceCream->Close();
}
}
void OpenOrder()
{
. . . No Change
}
};
int main(array<System::String ^> ^args)
{
. . . No Change
Console::WriteLine();
return 0;
}
Execute the application and test it. Here is an example:
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Ice Scream Vending Machine
-----------------------------------
What type of flavor do you want?
1 - Vanilla
2 - Cream of Cocoa
3 - Chocolate Chip
4 - Organic Strawberry
5 - Butter Pecan
6 - Cherry Coke
7 - Chocolate Brownies
8 - Caramel Au Lait
9 - Chunky Butter
10 - Chocolate Cookie
Your Choice? 8
-----------------------------------
What type of container do you want?
1 - Cone
2 - Cup
3 - Bowl
Your Choice? 2
-----------------------------------
Do you want an ingredient or not
1 - No Ingredient
2 - Peanuts
3 - M & M
4 - Cookies
Your Choice? 3
-----------------------------------
How many scoops(1, 2, or 3)? 2
-----------------------------------
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Ice Scream Order
-----------------------------------
Flavor: Caramel Au Lait
Container: Cup
Ingredient: M & M
Scoops: 2
Total Price: $3.10
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Do you want us to remember this order the next time you come to get your ice scr
eam (y/n)? Y
Please enter your initials or the name we will use to remember your order: LS
=-= Ice Scream Vending Machine =-=
Saving Order: LS.icr
Press any key to continue . . .
Close the DOS window
Stream Reading |
|
As opposed to writing to a stream, you may want to read existing data from it. Before doing this, you can first specify your intent to the streaming class using the FileMode enumerator. This can be done using the FileStream class as follows:
using namespace System;
using namespace System::IO;
int main()
{
String ^ NameOfFile = L"Persons.spr";
/*
FileStream ^ fstPersons = gcnew FileStream(NameOfFile,
FileMode::Create);
BinaryWriter ^ wrtPersons = gcnew BinaryWriter(fstPersons);
wrtPersons->Write(L"James Bloch");
wrtPersons->Write(L"Catherina Wallace");
wrtPersons->Write(L"Bruce Lamont");
wrtPersons->Write(L"Douglas Truth");
wrtPersons->Close();
fstPersons->Close();
*/
FileStream ^ fstPersons = gcnew FileStream(NameOfFile, FileMode::Open);
return 0;
}
Once the stream is ready, you can get prepared to read data from it. To support this, you can use the BinaryReader class. This class provides two constructors. One of the constructors (the first) has the following syntax:
public:
BinaryReader(Stream ^ input);
This constructor takes as argument a Stream value, which could be a FileStream object. After declaring a FileStream variable using this constructor, you can read data from it. To do this, you can call an appropriate method. This class provides an appropriate method for each primitive data type.
After using the stream, you should close it to reclaim the resources it was using. This is done by calling the Close() method.
Here is an example of using the mentioned methods:
using namespace System;
using namespace System::IO;
int main()
{
String ^ NameOfFile = L"Persons.spr";
/*
FileStream ^ fstPersons = gcnew FileStream(NameOfFile,
FileMode::Create);
BinaryWriter ^ wrtPersons = gcnew BinaryWriter(fstPersons);
wrtPersons->Write(L"James Bloch");
wrtPersons->Write(L"Catherina Wallace");
wrtPersons->Write(L"Bruce Lamont");
wrtPersons->Write(L"Douglas Truth");
wrtPersons->Close();
fstPersons->Close();
*/
FileStream ^ fstPersons = gcnew FileStream(NameOfFile,
FileMode::Open);
BinaryReader ^ rdrPersons = gcnew BinaryReader(fstPersons);
String ^ strLine = nullptr;
strLine = rdrPersons->ReadString();
Console::WriteLine(strLine);
strLine = rdrPersons->ReadString();
Console::WriteLine(strLine);
strLine = rdrPersons->ReadString();
Console::WriteLine(strLine);
strLine = rdrPersons->ReadString();
Console::WriteLine(strLine);
rdrPersons->Close();
fstPersons->Close();
Console::WriteLine();
return 0;
}
This would produce:
James Bloch
Catherina Wallace
Bruce Lamont
Douglas Truth
Press any key to continue . . .
Practical Learning: Reading From a Stream |
|
To be able to retrieve data from an existing file, change the IceCream.cs file as follows:
// IceCream3.cpp : main project file.
#include "stdafx.h"
using namespace System;
using namespace System::IO;
// This class is used to create and manage an ice scream
// and to process an order
public ref class CIceCream sealed
{
public:
// This is the base price of an ice scream
// Optional values may be added to it
static const double BasePrice = 1.55;
// These arrays are used to build the components
// of various ice screams
private:
array<String ^> ^ Flavor;
array<String ^> ^ Container;
array<String ^> ^ Ingredient;
// Additional factor used to process an ice scream order
int Scoops;
double TotalPrice;
// Variables that will hold the user's choice
// These are declared "globally" so they can be
// shared among methods
int ChoiceFlavor;
int ChoiceContainer;
int ChoiceIngredient;
// This default constructor is the best place for
// us to initialize the array
public:
CIceCream()
{
Flavor = gcnew array<String ^>(10);
Flavor[0] = L"Vanilla";
Flavor[1] = L"Cream of Cocoa";
Flavor[2] = L"Chocolate Chip";
Flavor[3] = L"Organic Strawberry";
Flavor[4] = L"Butter Pecan";
Flavor[5] = L"Cherry Coke";
Flavor[6] = L"Chocolate Brownies";
Flavor[7] = L"Caramel Au Lait";
Flavor[8] = L"Chunky Butter";
Flavor[9] = L"Chocolate Cookie";
Ingredient = gcnew array<String^>(4);
Ingredient[0] = L"No Ingredient";
Ingredient[1] = L"Peanuts";
Ingredient[2] = L"M & M";
Ingredient[3] = L"Cookies";
Container = gcnew array<String^>(3);
Container[0] = L"Cone";
Container[1] = L"Cup";
Container[2] = L"Bowl";
}
// This method requests a flavor from the user and
// returns the choice
void ChooseFlavor()
{
// Make sure the user selects a valid number
//that represents a flavor...
do {
// In case the user types a symbol that
// is not a number
try {
Console::WriteLine(L"What type of flavor do you want?");
for (int i = 0; i < Flavor->Length; i++)
Console::WriteLine(L"{0} - {1}", i + 1, Flavor[i]);
Console::Write(L"Your Choice? ");
ChoiceFlavor = int::Parse(Console::ReadLine());
}
catch(FormatException ^) // display an appropriate message
{
Console::WriteLine(L"You must enter a valid number "
L"and no other character!");
}
// If the user typed an invalid number out of the
// allowed range
// let him or her know and provide another chance
if( ChoiceFlavor < 1 || ChoiceFlavor > Flavor->Length)
Console::WriteLine(L"Invalid Choice - Try Again!\n");
} while (ChoiceFlavor < 1 || ChoiceFlavor > Flavor->Length);
}
// This method allows the user to select a container
void ChooseContainer()
{
// Make sure the user selects a valid number that
// represents a container
do {
// If the user types a symbol that is not a number
try
{
Console::WriteLine(L"What type of container do you want?");
for (int i = 0; i < Container->Length; i++)
Console::WriteLine(L"{0} - {1}", i + 1, Container[i]);
Console::Write(L"Your Choice? ");
ChoiceContainer = int::Parse(Console::ReadLine());
}
catch (FormatException ^) // display an appropriate message
{
Console::WriteLine(L"You must enter a valid "
L"number and no other character!");
}
// If the user typed an invalid number out of the
// allowed range
// let him or her know and provide another chance
if( (ChoiceContainer < 1) ||
(ChoiceContainer > Container->Length) )
Console::WriteLine(L"Invalid Choice - Try Again!");
} while ((ChoiceContainer < 1) ||
(ChoiceContainer > Container->Length));
}
void ChooseIngredient()
{
do {
try {
Console::WriteLine(L"Do you want an ingredient or not");
for (int i = 0; i < Ingredient->Length; i++)
Console::WriteLine(L"{0} - {1}",
i + 1, Ingredient[i]);
Console::Write(L"Your Choice? ");
ChoiceIngredient = int::Parse(Console::ReadLine());
}
catch (FormatException ^)
{
Console::WriteLine(L"You must enter a valid "
L"number and no other character!");
}
if( (ChoiceIngredient < 1) ||
(ChoiceIngredient > Ingredient->Length) )
Console::WriteLine(L"Invalid Choice - Try Again!");
} while ((ChoiceIngredient < 1) ||
(ChoiceIngredient > Ingredient->Length));
}
void SpecifyNumberOfScoops()
{
do {
try {
Console::Write(L"How many scoops(1, 2, or 3)? ");
Scoops = int::Parse(Console::ReadLine());
}
catch (FormatException ^)
{
Console::WriteLine(L"You must enter a valid number "
L"and no other character!");
}
if( Scoops < 1 || Scoops > 3 )
Console::WriteLine(L"Invalid Choice - Try Again!");
} while (Scoops < 1 || Scoops > 3);
}
// This method is used to process a customer order
// It uses the values of the above methods
void ProcessAnOrder()
{
double PriceIngredient, PriceScoop;
// Let the user know that this is a vending machine
Console::WriteLine(L"=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
Console::WriteLine(L"Ice Scream Vending Machine");
Console::WriteLine(L"-----------------------------------");
// Let the user select the components of the ice scream
ChooseFlavor();
Console::WriteLine(L"-----------------------------------");
ChooseContainer();
Console::WriteLine(L"-----------------------------------");
ChooseIngredient();
Console::WriteLine(L"-----------------------------------");
SpecifyNumberOfScoops();
Console::WriteLine(L"-----------------------------------");
// If the user selects an ingredient instead of "No Ingredient",
// add $0.50 to the order
if( (ChoiceIngredient == 2) ||
(ChoiceIngredient == 3) ||
(ChoiceIngredient == 4) )
PriceIngredient = 0.50;
else
PriceIngredient = 0.00;
// Instead of multiplying a number scoops to a value,
// We will use an incremental value depending on
// the number of scoops
if( Scoops == 1 )
PriceScoop = 0.65;
else if( Scoops == 2 )
PriceScoop = 1.05;
else
PriceScoop = 1.55;
// Calculate the total price of the ice scream
TotalPrice = BasePrice + PriceScoop + PriceIngredient;
// Create the ice scream...
// And display a receipt to the user
DisplayReceipt();
}
// This method is used to display a receipt to the user
void DisplayReceipt()
{
Console::WriteLine(L"\n=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=");
Console::WriteLine(L"Ice Scream Order");
Console::WriteLine(L"-----------------------------------");
Console::WriteLine(L"Flavor: {0}",
Flavor[ChoiceFlavor - 1]);
Console::WriteLine(L"Container: {0}",
Container[ChoiceContainer - 1]);
Console::WriteLine(L"Ingredient: {0}",
Ingredient[ChoiceIngredient - 1]);
Console::WriteLine(L"Scoops: {0}", Scoops);
Console::WriteLine(L"Total Price: {0:C}", TotalPrice);
Console::WriteLine(L"=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=\n");
}
void SaveOrder()
{
String ^ strNameOfFile;
Console::Write(L"Please enter your initials or the name "
L"we will use to remember your order: ");
strNameOfFile = Console::ReadLine();
strNameOfFile = strNameOfFile + L".icr";
// Find out if the user entered a name of a file
// that is already in the machine
if( File::Exists(strNameOfFile) )
{
char answer;
FileStream ^ stmIceCream =
gcnew FileStream(strNameOfFile, FileMode::Create);
BinaryWriter ^ bnwIceCream =
gcnew BinaryWriter(stmIceCream);
// If so, find out if the user wants to
// replace the old file
Console::WriteLine(L"The file you entered exists already.");
Console::Write(L"Do you want to replace it(y/n)?");
answer = char::Parse(Console::ReadLine());
// If the customer wants to replace it...
if( (answer == L'y') || (answer == 'Y') )
{
// ... do so
Console::WriteLine(L"The former order with the same "
L"name will be replaced");
Console::WriteLine(L"\n=-= Ice Scream Vending Machine =-=");
Console::WriteLine(L" Saving Order: {0}", strNameOfFile);
bnwIceCream->Write(Flavor[ChoiceFlavor - 1]);
bnwIceCream->Write(Container[ChoiceContainer - 1]);
bnwIceCream->Write(Ingredient[ChoiceIngredient - 1]);
bnwIceCream->Write(Scoops);
bnwIceCream->Write(TotalPrice);
}
// If the customer wants to save the new order with
// a different name
else if( (answer == L'n') || (answer == 'N') )
{
// Ask the user to enter a name to remember the order
Console::Write(L"Please enter a name we will use "
L"to remember this order: ");
strNameOfFile = Console::ReadLine();
strNameOfFile = strNameOfFile + L".icr";
stmIceCream = gcnew FileStream(strNameOfFile, FileMode::Create);
bnwIceCream = gcnew BinaryWriter(stmIceCream);
Console::WriteLine(L"\n=-= Ice Scream Vending Machine =-=");
Console::WriteLine(L" Saving Order: {0}", strNameOfFile);
bnwIceCream->Write(Flavor[ChoiceFlavor - 1]);
bnwIceCream->Write(Container[ChoiceContainer - 1]);
bnwIceCream->Write(Ingredient[ChoiceIngredient - 1]);
bnwIceCream->Write(Scoops);
bnwIceCream->Write(TotalPrice);
}
else
Console::WriteLine(L"Invalid Answer - We will close");
bnwIceCream->Close();
stmIceCream->Close();
}
else
{
FileStream ^ stmIceCream =
gcnew FileStream(strNameOfFile, FileMode::Create);
BinaryWriter ^ bnwIceCream =
gcnew BinaryWriter(stmIceCream);
Console::WriteLine(L"\n=-= Ice Scream Vending Machine =-=");
Console::WriteLine(L" Saving Order: {0}", strNameOfFile);
bnwIceCream->Write(Flavor[ChoiceFlavor - 1]);
bnwIceCream->Write(Container[ChoiceContainer - 1]);
bnwIceCream->Write(Ingredient[ChoiceIngredient - 1]);
bnwIceCream->Write(Scoops);
bnwIceCream->Write(TotalPrice);
bnwIceCream->Close();
stmIceCream->Close();
}
}
void OpenOrder()
{
String ^ strNameOfFile;
String ^ SelectedFlavor;
String ^ SelectedContainer;
String ^ SelectedIngredient;
// Ask the user to enter a name of a previously saved order
Console::Write(L"Please enter the name you previously "
L"gave to remember your order: ");
strNameOfFile = Console::ReadLine();
strNameOfFile = strNameOfFile + L".icr";
FileStream ^ stmIceCream =
gcnew FileStream(strNameOfFile, FileMode::Open);
BinaryReader ^ bnrIceCream =
gcnew BinaryReader(stmIceCream);
// Find out if this order was previously saved in the machine
if( File::Exists(strNameOfFile) )
{
// If so, open it
SelectedFlavor = bnrIceCream->ReadString();
SelectedContainer = bnrIceCream->ReadString();
SelectedIngredient = bnrIceCream->ReadString();
Scoops = bnrIceCream->ReadInt32();
TotalPrice = bnrIceCream->ReadDouble();
// And display it to the user
Console::WriteLine(L"\n=-= Ice Scream Vending Machine =-=");
Console::WriteLine(L" Previous Order: {0}", strNameOfFile);
Console::WriteLine(L"Flavor: {0}", SelectedFlavor);
Console::WriteLine(L"Container: {0}", SelectedContainer);
Console::WriteLine(L"Ingredient: {0}", SelectedIngredient);
Console::WriteLine(L"Scoops: {0}", Scoops);
Console::WriteLine(L"Total Price: {0:C}\n", TotalPrice);
bnrIceCream->Close();
stmIceCream->Close();
}
else
Console::WriteLine(L"The name you entered is not "
L"registered in our previous orders");
}
};
int main(array<System::String ^> ^args)
{
String ^ answer = L"n";
CIceCream ^ ic = gcnew CIceCream();
Console::Write(L"Do you want to re-order a previously "
L"saved order(y/n)? ");
answer = Console::ReadLine();
if( (answer == L"y") || (answer == L"Y") )
ic->OpenOrder();
else
{
ic->ProcessAnOrder();
Console::Write(L"Do you want us to remember this "
L"order the next time you come to "
L"get your ice scream (y/n)? ");
answer = Console::ReadLine();
if( (answer == L"y") || (answer == L"Y") )
ic->SaveOrder();
else
Console::WriteLine(L"\nIt was nice serving you."
L"\nCome Again!!!\n");
}
Console::WriteLine();
return 0;
}
Execute the application and test it. Here is an example:
Do you want to re-order a previously saved order(y/n)? Y
Please enter the name you previously gave to remember your order: LS
=-= Ice Scream Vending Machine =-=
Previous Order: LS.icr
Flavor: Caramel Au Lait
Container: Cup
Ingredient: M & M
Scoops: 2
Total Price: $3.10
Press any key to continue . . .
Close the DOS window
Execute the application again and test it. Here is an example:
Do you want to re-order a previously saved order(y/n)? w
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Ice Scream Vending Machine
-----------------------------------
What type of flavor do you want?
1 - Vanilla
2 - Cream of Cocoa
3 - Chocolate Chip
4 - Organic Strawberry
5 - Butter Pecan
6 - Cherry Coke
7 - Chocolate Brownies
8 - Caramel Au Lait
9 - Chunky Butter
10 - Chocolate Cookie
Your Choice? 5
-----------------------------------
What type of container do you want?
1 - Cone
2 - Cup
3 - Bowl
Your Choice? 2
-----------------------------------
Do you want an ingredient or not
1 - No Ingredient
2 - Peanuts
3 - M & M
4 - Cookies
Your Choice? 1
-----------------------------------
How many scoops(1, 2, or 3)? 1
-----------------------------------
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Ice Scream Order
-----------------------------------
Flavor: Butter Pecan
Container: Cup
Ingredient: No Ingredient
Scoops: 1
Total Price: $2.20
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Do you want us to remember this order the next time
you come to get your ice scream (y/n)? y
Please enter your initials or the name we will use
to remember your order: DIC
=-= Ice Scream Vending Machine =-=
Saving Order: DIC.icr
Press any key to continue . . .
Close the DOS window
Execute the application again and test it. Here is an example:
Do you want to re-order a previously saved order(y/n)? n
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Ice Scream Vending Machine
-----------------------------------
What type of flavor do you want?
1 - Vanilla
2 - Cream of Cocoa
3 - Chocolate Chip
4 - Organic Strawberry
5 - Butter Pecan
6 - Cherry Coke
7 - Chocolate Brownies
8 - Caramel Au Lait
9 - Chunky Butter
10 - Chocolate Cookie
Your Choice? 9
-----------------------------------
What type of container do you want?
1 - Cone
2 - Cup
3 - Bowl
Your Choice? 3
-----------------------------------
Do you want an ingredient or not
1 - No Ingredient
2 - Peanuts
3 - M & M
4 - Cookies
Your Choice? 4
-----------------------------------
How many scoops(1, 2, or 3)? 3
-----------------------------------
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Ice Scream Order
-----------------------------------
Flavor: Chunky Butter
Container: Bowl
Ingredient: Cookies
Scoops: 3
Total Price: $3.60
=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=
Do you want us to remember this order the next time
you come to get your ice scream (y/n)? Y
Please enter your initials or the name we will use
to remember your order: LS
The file you entered exists already.
Do you want to replace it(y/n)?Y
The former order with the same name will be replaced
=-= Ice Scream Vending Machine =-=
Saving Order: LS.icr
Press any key to continue . . .
Close the DOS window
