Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.

Similar presentations


Presentation on theme: "1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together."— Presentation transcript:

1 1 Lecture 19 Structs HW 5 has been posted

2 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together to form a new more complex data type. n you can use this new data type to declare variables n you can create vectors with this new data type l Place struct definitions at the beginning of a program, after include lines and before functions and function prototypes. l To access the components of a struct, use the dot operator. n can be used anywhere an ordinary variable can be used struct { ;... }; struct acct { int acctnum; string name; float balance; }; acctmyAccount; myAccount.acctnum = 99999; myAccount.name = “Nate”; myAccount.balance = 10000;

3 3 struct acct // Create bank account data type struct acct { // does not allocate memory int num; string name; floatbalance; }; int main() { … acct thisAcct ; // declare variables of acct acct anotherAcct ;

4 4 thisAcct 5000.num 2037581.name “Sylvester”.balance 150.00.num 2037582.name “Tweedy”.balance 2045.80 6000 anotherAcct

5 5 struct type declarations If the struct type declaration precedes all functions it will be visible throughout the rest of the file. If it is placed within a function, only that function can use it. It is common to place struct type declarations with TypeNames in a (.h) header file and #include that file.

6 6 Use the dot to access struct members acct thisAcct;// declare variable for an account thisAcct.balance += 100; thisAcct.num = 2037581; cin >> thisAcct.balance; getline ( cin, thisAcct.name ); thisAcct.name[ 0 ] = toupper (thisAcct.name[ 0 ] ) ;

7 7 struct Operations l I/O, arithmetic, and comparisons of entire struct variables are NOT ALLOWED! l operations valid on an entire struct type variable: assignment to another struct variable of same type, pass to a function as argument (by value or by reference), return as value of a function

8 8 Examples of legal struct operations anotherAccount = thisAcount ; // assignment writeOut(thisAccount, cout); // value parameter deposit(thisAccount, 100); // reference parameter thisAccount = getAccountData( ); // return value of // function NOW WE’LL WRITE THE 3 FUNCTIONS USED HERE...

9 9 void writeOut(acct thisAcct, ostream & out) // Prints out values of all members of thisAcct // Precondition: all members of thisAcct are assigned // Postcondition: all members have been written out { out << “Account # ” << thisAcct.num << thisAcct.name << endl ; out << “Name: ” << thisAcct.name << endl ; out << “Balance $” << setprecision(2) << thisAcct.balance << endl ; } * Note that the struct acct is not passed by reference because we do not want to change it in the function. Also note the second paramenter is of type ostream (which allows us to call it with a filename OR cout). 9

10 10 void deposit ( /* inout */ acct & thisAcct, float amount) // Adds amount to balance // Precondition: thisAccount.balance is assigned // Postcondition: thisAcct.balance = thisAcct.balance @entry + amount { thisAcct.balance += amount ; } Passing a struct Type by Reference

11 11 acct getAccountData ( ) // Obtains all information about an account from keyboard // Postcondition: // Function value == acct members entered at kbd { acct thisAcct ; char response ; do {// have user enter all members until they are correct. } while (response != ‘Y’ ) ; return thisAcct ; } 11

12 12 Bank Simulation (1) #include using namespace std; // Create bank account data type struct acct { // bank account data int num; // account number string name; // owner of account floatbalance; // balance in account }; // Function Prototypes int find(vector bank, int goal); void writeOut(acct a, ostream & out); acct getAccountData(); l This program simulates a bank by processing transactions for bank accounts. l A vector is used to hold the list of bank accounts. l A bank account consists of an account number, the name of the person who owns it, and the current balance. n we need a way to combine these three pieces of data into a single piece of account data n we will use a C++ struct to do this

13 13 Bank Simulation (2) int main () { // list of bank accounts vector bank; // total number of accounts intnumaccts; // file with list of bank accounts ifstream vault (“accounts.txt”); // user request stringcommand; // account number to find intgoal; l The main function creates the list of bank accounts and processes user commands to perform transactions. l We want the vector to be a list of variable length n we do not know how many bank accouts the file has l The existing accounts are read from a file at the start of the program. n add each to the bank vector l User commands are typed as strings (e.g., find, insert, exit).

14 14 Bank Simulation (3) // subscript of account in bank intloc; // a bank account acctaccount; // read existing accounts from file vault.open("accounts.txt"); vault >> account.num >> account.name >> account.balance; while (vault) { bank.push_back(account); vault >> account.num >> account.name >> account.balance; } // display dollar values correctly cout << fixed << setprecision(2); l The program assumes that a file named accounts.txt contains the data for existing accounts. l This is the while loop for reading data until the end of file. l Dollar values should be displayed with two digits to the right of the decimal point. n the last two lines instruct the cout object to do this when displaying float values

15 15 Bank Simulation (4) // loop to process user commands cout << "Enter command " << "(exit to stop): "; cin >> command; while (command != “exit”) { if (command == "find") { // get account to find cout << "Enter account num: "; cin >> goal; // search for account loc = find(bank, goal); if (loc >= 0) writeOut(bank[loc]); else { cout << "Account " << goal <<" does not exist." <<endl; } l Use the standard while loop to get commands from the user until the user enters the exit command. l User commands are processed inside the loop. n since commands are strings, can’t use a switch statement n therefore, use nested IF- ELSE statements l First case is the find command. n get account number to find from user n call function find to search the account list for this account n Find returns -1 if not found

16 16 Function Find int find(vector bank, int goal) { int k;// loop variable // search for the goal account in // the list of accounts for (k=0; k<bank.size(); k++) { if (bank[k].num == goal) return k; } // didn't find goal account return -1; } l Parameters: list of accounts, number of the goal account to find. l Return: subscript of goal account if found, or –1 to indicate that it is not in the list. l Search the list from its beginning, element by element until: n find the account n reach the end of the list l This is called a sequential search.

17 17 Bank Simulation (5) else if (command == "list") { // LIST COMMAND cout << "List of accounts:" << endl; for (loc=0; loc<bank.size(); loc++) { writeOut(bank[loc], cout); cout << endl; } l The second case inside the while loop that processes user commands is the list command. l Display the account data for all accounts in the account list.

18 18 Bank Simulation (6) else if (command == "insert") { acct newacct = getAccountData(); bank.push_back(newacct); } l The third case inside the while loop that processes user commands is the insert command. l In this case we call the getAccountData function to prompt the user for data. This function returns an acct. l We push that acct onto the end of the bank

19 19 Bank Simulation (7) else { // INVALID COMMAND cout << "Invalid command." << endl; } cout << "Enter a command "; << "(exit to stop): "; cin >> command; } // exit command from user cout << "The bank is now closed."; cout << endl << endl; return 0; } l The final case in the while loop processing user commands is the default case for invalid commands. n display a suitable error message l When the user types the exit command, the while loop terminates. n display a message closing the bank and terminate the program n a “real” bank program would write the new account list to a file n this file would be loaded into the program the next time it runs

20 20 C++ Data Type class l Classes are very similar to structs, as they group related data together, and allow programmers to use “member functions” that manipulate that data. l 2 kinds of class members: data members and function members l You will learn much more about classes in CS 2.


Download ppt "1 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together."

Similar presentations


Ads by Google