Programming Initializing Data of Struct Type. COMP102 Prog. Fundamentals: initialize struct type/ Slide 2 Ex. 10: Initialize Data of struct Type l By.

Slides:



Advertisements
Similar presentations
Array. Convert Numbers in Different Base Systems Generate values to a series of numbers in different base systems: Base is between 2 and 9; Maximum number.
Advertisements

1 Programming Structures COMP102 Prog. Fundamentals, Structures / Slide 2 2 Structures l A Structure is a collection of related data items, possibly.
Programming Functions: Passing Parameters by Reference.
CMSC 2021 C++ I/O and Other Topics. CMSC 2022 Using C++ Stream I/O Default input stream is called cin Default output stream is called cout Use the extraction.
File Input/Output. External Files Batch –Requires use of data files (save to disk) –Batch can be run during off peak use –allows things to be complete.
CS 1620 File I/O. So far this semester all input has been from keyboard all output has been to computer screen these are just two examples of where to.
1 Text File I/O Chapter 6 Pages File I/O in an Object-Oriented Language Compare to File I/O in C. Instantiate an ofstream object. Like opening.
While Loops Programming. COMP102 Prog Fundamentals I: while Loops/Slide 2 Shortcut Assignments l C++ has a set of shortcut operators for applying an operation.
Arrays Programming COMP102 Prog. Fundamentals I: Arrays / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g.,
More on Functions Programming. COMP104 Lecture 19 / Slide 2 Passing Parameters by Reference l To have a function with multiple outputs, we have to use.
1 Programming with Data Files Chapter 4 2 Standard Input Output C++ Program Keyboard input cin Output Screen cout.
Array Application Programming. COMP102 Prog. Fundamentals I: Arrays Application / Slide 2 Character Array: Ex. 1 l Note: a palindrome is a word (or words)
Programming Strings. COMP102 Prog. Fundamentals: Strings / Slide 2 Character Strings l A sequence of characters is often referred to as a character “string”.
COMP102 – Programming Fundamentals I LA2B (Mon 5-7pm) LA2E (Fri 3-5pm) LA2F (Fri 5-7pm) TA: Jackie Lo.
Structures COMP104 Structs / Slide 2 Motivation: a new type * Structures hold data that belong together. * Examples: n Student record  student id, name,
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
Pass by Reference. COMP104 Pass by Reference / Slide 2 Passing Parameters by Reference * To have a function with multiple outputs, we have to use pass.
Programming Functions: Passing Parameters by Reference.
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Chapter 8 Data File Basics.
Structured Data Types array array union union struct struct class class.
1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters.
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
Module 4: Structures ITEI222 Advanced Programming.
1 CS161 Introduction to Computer Science Topic #13.
 Introduction to Computer Science COMP 51 – Fall 2012 – Section 2 Structures.
C++ Review Some things you’re supposed to know. Your Background n Should have CSC 226/227 or equivalent  selection commands: if, switch  repetition.
Define our own data types We can define a new data type by defining a new class: class Student {...}; Class is a structured data type. Can we define our.
C++ Streams © Bruce M. Reynolds & Cliff Green, C++ Programming Certificate University of Washington Cliff Green.
File I/O in C++ II. Open() function Open() is a member function in each classes ( fstream, ifstream, ofstream) Void fstream :: open ( const char *filename,
Structured Data Types struct class Structured Data Types array – homogeneous container collections of only one type struct – heterogeneous data type.
Structures - Part II aggregate operations arrays of type struct nested structures compared to classes.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
Programming Final Review COMP102 Prog. Fundamentals I: Character I/O/ Slide 2 Scope n The scope of an identifier does not apply if the same identifier.
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
Quiz // // The function exchanges the two parameters. // Param: ( ) // Param:
Arrays Dr. Jose Annunziato. Arrays Up to this point we have been working with individual primitive data types Arrays allow working with multiple instances.
Chapter 11 Standard C++ Strings and File I/O Dept of Computer Engineering Khon Kaen University.
Data Types Storage Size Domain of all possible values Operations 1.
Struct COMP104 Struct / Slide 2 Motivation * Structures hold data that belong together. * Examples: n Student record  student id, name, major, gender,
COMP102 Lab 111 COMP 102 Programming Fundamentals I Presented by : Timture Choi.
Files To read a file – We must know its name – We must open it (for reading) – Then we can read – Then we must close it That is typically done implicitly.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
File I/O in C++. Using Input/Output Files A computer file  is stored on a secondary storage device (e.g., disk);  is permanent;  can be used to provide.
Writing to Files and Reading From Files. Writing Data to a File Creating a new file, a.dat or.txt file #include #include // for file writing #include.
Exception Handling How to handle the runtime errors.
File I/O in C++ I. Using Input/Output Files A computer file is stored on a secondary storage device (e.g., disk); is permanent; can be used to provide.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
File Processing.
MT262A Review.
C++ Arrays.
Parallel Arrays Parallel array =>Two or more arrays with the same number of elements used for storing related information about a collection of data. Example:
CS 1430: Programming in C++.
Structures A Structure is a collection of related data items, possibly of different types. A structure type in C++ is called struct. A struct is heterogeneous.
Basic File I/O and Stream Objects
Text Files All the programs you've seen so far have one thing in common: Any data the program uses or calculates is lost when the program ends. In order.
Standard Input/Output Stream
CS150 Introduction to Computer Science 1
Formatted Input, Output & File Input, Output
CS150 Introduction to Computer Science 1
CPS120: Introduction to Computer Science
CHAPTER 4 File Processing.
Reading from and Writing to Files
Programming with Data Files
Programming Structures.
Programming Structures.
File I/O in C++ II.
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
Reading from and Writing to Files Part 2
Reading from and Writing to Files
Presentation transcript:

Programming Initializing Data of Struct Type

COMP102 Prog. Fundamentals: initialize struct type/ Slide 2 Ex. 10: Initialize Data of struct Type l By assignment during declaration; example : struct StudentRecord { // student record double totalgrade; char name[name_size], id[id_size]; int grade[no_grades]; }; StudentRecord student1 = { 0.0, "CHAN Tai Man", " ", {80, 67, 34, 67} };

COMP102 Prog. Fundamentals: initialize struct type/ Slide 3 Initialization of a “ nested ” structure: struct Point { int x, y; }; //defines the coordinates of a point struct Triangle { Point vertex[3]; double area; }; //defines a triangle Triangle tlist[2] = { {{{0, 0}, {1, 0}, {0, 1}}, 0.5}, // 1st Triangle {{{2, 0}, {3, 0}, {3, 1}}, 0.5} // 2nd Triangle }; Ex. 11: Initialize Data of struct Type

COMP102 Prog. Fundamentals: initialize struct type/ Slide 4 Ex. 12: Using struct Type in Functions 1. As parameters: both pass-by-value and pass-by-reference are supported. 2. As type of function: assembly of return value needed. Example of case 2: StudentRecord shrink_wrap( // a function with const char sname[], // name shrink_wrap of const char sid[], // type StudentRecord const int sgrade[]) { StudentRecord temp; temp.totalgrade = 0; strcpy (temp.name, sname); strcpy (temp.id, sid); for (int index=0; index<no_grades; index++) temp.grade[index] = sgrade[index]; return temp; } // Defines an initialization function

COMP102 Prog. Fundamentals: initialize struct type/ Slide 5 Ex. 12: Using struct Type in Functions StudentRecord student1; int scores[4] = {80, 67, 34, 67}; student1 = shrink_wrap ("CHAN Tai Man", " ", scores}; has the same effect of: StudentRecord student1 = { 0.0, "CHAN Tai Man", " ", {80, 67, 34, 67} };

COMP102 Prog. Fundamentals: initialize struct type/ Slide 6 Ex. 13: Big example Sample input data file "class102.txt" : Hello Kitty/ Hello Catty/ Minnie Mouse/ Mickey Mouse/ Sample output: Enter number of students: 4 Hello Kitty 9 Hello Catty 9 Minnie Mouse 64 Mickey Mouse 64

COMP102 Prog. Fundamentals: initialize struct type/ Slide 7 Classlist structure Classlist Class102; Classlist 049 clist no_tests size Student 019 name birthday score Date day month year Hello Kitty/ Hello Catty/ Minnie Mouse/ Mickey Mouse/

COMP102 Prog. Fundamentals: initialize struct type/ Slide 8 Ex. 13: Big example #include #include #include using namesapce std; const int name_size = 20, num_score= 5, class_size=50; struct Date{ int day; int month; int year; }; struct Student{ char name[name_size]; Date birthday; int score[num_score]; }; struct Classlist{ Student clist[class_size]; // list of max 50 students int no_tests; // number of completed tests int size; // number of students in clist };

int main(){ int csize; Date today = {6, 11, 2009}; Classlist COMP102; cout > csize; COMP102.no_tests = 3; COMP102.size = csize; in_class(COMP102); for (int index=0; index < csize; index++) cout << setw(25) << setiosflags(ios::left) << COMP102.clist[index].name << setw(25) << setiosflags(ios::left) << age(today, index, COMP102) << endl; return 0; }

COMP102 Prog. Fundamentals: initialize struct type/ Slide 10 Classlist structure // input file class102.txt Classlist COMP clist no_tests size Hello Kitty/ Hello Catty/ Minnie Mouse/ Mickey Mouse/

COMP102 Prog. Fundamentals: initialize struct type/ Slide 11 Classlist structure COMP102.Clist[0] Hello Kitty/ name birthday score Date day month year

void in_class(Classlist & Class){ // This function reads in the student records from the // input file stream and stores them in Class. ifstream in; in.open(“comp102.txt”); char temp; for (int index=0; index < Class.size; index++){ //read in the name in.getline(Class.clist[index].name, 19, '/'); in >> Class.clist[index].birthday.day; in >> Class.clist[index].birthday.month; in >> Class.clist[index].birthday.year; for (int count=0; count > Class.clist[index].score[count]; in.get(temp); // read carriage return } in.close(); }

int age(Date today, int index, Classlist c){ // This function computes the age in years for the // student at the index position in c. int csize; csize = c.size; if (index < csize) if (c.clist[index].birthday.month < today.month) return (today.year - c.clist[index].birthday.year); else if(c.clist[index].birthday.month == today.month) if (c.clist[index].birthday.day <= today.day) return (today.year - c.clist[index].birthday.year); else return (today.year c.clist[index].birthday.year); else return (today.year c.clist[index].birthday.year); else{ cout << "Error: index out of range \n"; return 0; } } // end-of-age

COMP102 Prog. Fundamentals: initialize struct type/ Slide 14 Ex. 14: Using struct Type in Functions The next example adds student records into a file, and can list all the student records in that file: sample output: Please enter choice: 0 - Exit 1 - Add a record 2 - List all records 1 Pls enter name: Mickey Mouse Pls enter id: Pls enter

#include using namesapce std; void get_choice(int& pick_number); void process_choice(int pick_number); struct student_info{ char name[22]; char id[9]; char [22]; }; int main(){ int pick_number = 1; do{ get_choice(pick_number); process_choice(pick_number); }while (pick_number); return 0; }

void get_choice(int& choice) { do { cout << "Please enter choice:" << endl; cout << " 0 - Exit" << endl; cout << " 1 – Add a record" << endl; cout << " 2 - List all records" << endl; cin >> choice; } while (choice != 0 && choice != 1 && choice != 2); cin.ignore(256, '\n'); }

void add_record(const char student_record[]){ ofstream outfile; struct student_info top_gun; cout << "Pls enter name: "; cin.getline(top_gun.name, 21); cout << "Pls enter id: "; cin >> top_gun.id; cout << "Pls enter "; cin >> top_gun. ; //ios::app - opening file for appending outfile.open(student_record, ios::app); if(outfile){ // If no error occurred while opening file outfile << top_gun.name << '\t'; outfile << top_gun.id << '\t'; outfile << top_gun. << '\n'; } else cout << "Error...." << endl; outfile.close(); }

void list_record(const char student_record[]){ ifstream infile; char x; //ios::in - opening file for input infile.open(student_record); infile.getline(temp,80); while(!infile.eof()){ cout << temp << endl; infile.getline(temp,80); } infile.close(); }

void process_choice(int choice){ if (choice == 1) add_record("data.txt"); else if(choice == 2) list_record("data.txt"); else if (choice == 0) cout << "You have chosen to exit the program.\n" else cout << "Wrong choice, program aborted." << endl; }