Top Banner
1/31 Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q&A Conclusion References Files CSC-201 - Computer Science I Lecture #6: Chapter 8 Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge Dr. Chuck Cartledge September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm September 26, 2016 at 4:01pm
31

CSC-201 - Computer Science I Lecture #6: Chapter 8ccartled/Teaching/2016-Fall-TCC/Lectures/006.pdfTest Results Schedule MiscellaneaChap. 7 Chap. 8BreakHands onQ & AConclusionReferencesFiles

Oct 11, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 1/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    CSC-201 - Computer Science ILecture #6: Chapter 8

    Dr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck Cartledge

    September 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pmSeptember 26, 2016 at 4:01pm

  • 2/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Table of contents I

    1 Test Results

    2 Schedule

    3 Miscellanea

    4 Chap. 7

    5 Chap. 8

    6 Break

    7 Hands on

    8 Q & A

    9 Conclusion

    10 References

    11 Files

  • 3/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Histograms

    Histogram of questions and misses

  • 4/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Histograms

    Histogram of letter grades

    Test scores are only part of your final grade. See syllabus.

  • 5/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Histograms

    Q & A time.

    “’The Answer to the GreatQuestion . . . Of Life, the Universeand Everything . . . is. . . forty-two,’ said DeepThought, with infinite majestyand calm.”Douglas Adams, TheHitchhiker’s Guide to theGalaxy

  • 6/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Schedule for the semester:

    Wk. Date Topic Wk. Date Topic1 08/22 Chaps. 1 – 2 X 9 10/17 Chap. 102 08/29 Chaps. 3 – 4 X 10 10/24 Chaps. 10 – 113 09/05 Chap. 5 X 11 10/31 Chaps. 10 – 114 09/12 Test – Chap. 6 X 12 11/07 Test– Chap. 145 09/19 Chap. 7 X1 13 11/14 Chap. 146 09/26 Chap. 8 14 11/28 Chap. 187 10/03 Chap. 9 15 12/05 Chap. 188 10/10 Test – Chap. 10 16 12/12 Exam

    Notes:

    1 Class canceled due to electrical fire in instructor’s home

  • 7/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Programming assignment #003

    File Based Address Book

    Objectives are fairly straightforward:

    Accept commands from the user

    Read strings from a data file

    Search strings for data from user

    Output strings to the screen in aparticular format, or outputmessage

    Submit your source code.

    This is a single person effort (not ateam effort).

    Due by start of class 4 Oct. 2016.

  • 8/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Programming assignment #003

    Q & A time.

    Q: What is the square root of4b2?A: To be or not to be.

    Now is the time to ask questions.

  • 9/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Corrections and additions since last lecture.

    Graded, and re-graded thetest

    Check syllabus to see howgrades are computed

    Homework for chapter 6 duebefore class

    Exchanged e-mails and hadoffice hours (videoconference)

    Started gradingprogramming assignment#002

    Lots of catching up to do.

  • 10/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    This and that

    Read from a file.

    Objectives are fairly straightforward:

    Read strings from a data file.

    First string is the key.

    Second string is the plain text.

    Output plain and “encrypted”strings to the screen in a particularorder

    Submit your source code.

    This is a single person effort (not ateam effort).

    Any questions or problems?

  • 11/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    The lecture is attached

  • 12/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Functional decomposition

    What are functions, and why should I care?

    “A function is a group of statements that together perform a task.

    Every C++ program has at least one function, which is main(), and all

    the most trivial programs can define additional functions.

    You can divide up your code into separate functions. How you divide up

    your code among different functions is up to you, but logically the division

    usually is so each function performs a specific task.

    A function declaration tells the compiler about a function’s name, return

    type, and parameters. A function definition provides the actual body of

    the function.

    The C++ standard library provides numerous built-in functions that your

    program can call. For example, function strcat() to concatenate two

    strings, function memcpy() to copy one memory location to another

    location and many more functions.”

    T. Staff [1]

  • 13/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Functional decomposition

    Every C++ has a main function

    C++ program execution starts with the main function.The main function has three different definitions:

    1 int main();

    The simplest definition, and one that we have become familiarwith.

    2 int main(int argc, char**argv)

    This form allows you to access command line arguments.

    3 int main(int argc, char**argv, char*arge[])

    This form allows you to access command line arguments andenvironmental variables.

    Use the one that matches your needs.

  • 14/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Functional decomposition

    Parts of a function

  • 15/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Functional decomposition

    Parts of a function

  • 16/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Functional decomposition

    Parts MUST match

  • 17/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Functional decomposition

    The heading, or declaration has to be processed beforeit is used.

    The compiler is interested in knowing three things about afunction:

    1 Type of return value (if any)

    2 Unique name of the function

    3 The types of values in the parameter list (if any)

    These function declarations are identical:

    1 int Cube (int n);

    2 int Cube (int); (This is sometimes called a “prototype.”)

    Prototypes are often in “header” files. They can also be in .cppfiles.From a human/readable perspective, the first one is personallypreferable.

  • 18/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Functional decomposition

    Some things about functions

    Notable things about functions are called:1 Temporary memory is allocated for

    1 Parameters2 Local variables3 Possibly, the returned value

    2 Flow of control starts at the first line in the function

    3 Flow of control continues until a return statement, or untilthe last closing curly brace.

    Flow control returns to the calling function.

  • 19/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Functional decomposition

    Differences between parameters and arguments

    Parameters are in theprototype and thedeclaration – they are usedby the preprocessor andcompiler

    Arguments are the “things”passed to the function –they are values created within the program. Argumentsappear in the code that callsthe function.

    Reference parameters allow thefunction to change values in thecalling function without using thereturn statement.

  • 20/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Functional decomposition

    Same image.

  • 21/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Functional decomposition

    Parameters that are “pass by value” and “pass byreference”1

    The & token means the parameteris a “pass by reference”.

    The called function can changevalues in the calling function byusing the “pass by reference”parameter.

    The called function can also returna value using the returnstatement.

    We’ll practice with this program during the “Hands On” segment.

    1Pass by reference is sometimes called “pass by address” or “pass bylocation.”

  • 22/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    User-Defined Functions (UDF) and void functions

    Difference between UDF and non-UDF

    Authorship.

    UDFs are written by the programmer. The programmer isresponsible for prototype, declaration, and body.

    non-UDFs are provided by someone else. That someone hascreated the prototype (usually available in a header file), hascreated and compiled the declaration and body (usuallyavailable in a library). The internals of a non-UDF may beavailable only via documentation.

    The programmer is still responsible for bringing together all therequired libraries and compilation units to successfully compile theapplication.

  • 23/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    User-Defined Functions (UDF) and void functions

    Void functions don’t return anything via a returnstatement

    That doesn’t mean they don’t do anything.

    Void functions can change values in the calling function byusing pass by reference parameters.

    Void functions can make changes in the outer environment(like the Operating System) that are invisible to the callfunction.

    Just because a function is of type void, that doesn’t mean itdoesn’t do anything. It just means that it doesn’t have a returnstatement.

  • 24/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    User-Defined Functions (UDF) and void functions

    Violation of an assertion causes termination

    Many applications are very datasensitive. If a function is givendata that violates itsexpectations, then it is possibleto terminate the program.a.out: main04.cpp:18:

    int main(int, char**,

    char**): Assertion ‘i>0’

    failed.Including the #define NDEBUG

    before the #includewill “turn off” all the assert

    statements.

  • 25/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    User-Defined Functions (UDF) and void functions

    Same image.

    Including the #define NDEBUG before the #includewill “turn off” all the assert statements.

  • 26/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Break time.

    Take about 10 minutes.

  • 27/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Practice exercises

    Programs to load into CodeBlocks and get running:

    1 complex main function (See all the things available to yourprogram)

    2 pass by reference (fill out the body of the function and get itworking)

    Others, if you have time.

  • 28/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Q & A time.

    Q: How do you shoot a blueelephant? A: With ablue-elephant gun.Q: How do you shoot a pinkelephant? A: Twist its trunkuntil it turns blue, then shoot itwith a blue-elephant gun.

  • 29/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    What have we covered?

    Returned and discussed test #01Covered chapter 7Covered looping statements indifferent formsTalked about low level C++operatorsCovered chapter 8Talked about functions in differentforms and flavors

    Next time: Chapter 8 homework before class, Chapter 9

  • 30/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    References I

    [1] TutorialsPoint Staff, C++ functions, https://www.tutorialspoint.com/cplusplus/cpp_functions.htm,2016.

    https://www.tutorialspoint.com/cplusplus/cpp_functions.htmhttps://www.tutorialspoint.com/cplusplus/cpp_functions.htm

  • 31/31

    Test Results Schedule Miscellanea Chap. 7 Chap. 8 Break Hands on Q & A Conclusion References Files

    Files of interest

    1 if.cpp (just to start)

    2 switch.cpp (to expand)

    3 switches.cpp (to expand)

    4 Programming assignment #003

    5 Chapter 7 lecture

    6 simplest main function

    7 simple main function

    8 complex main function

    9 function calls (both good and bad)

    10 practice on pass by reference

    11 data file for pass by reference

    12 a program that violates and

    assertion

    if.cpp#include

    using namespace std;

    int main()

    {

      int inputInt;

      

      cout  inputInt;

      cout 

  • CSC-201 Fall 2016Assignment #3: File Based Address Book

    Due: Oct. 4, 2016

    Dr. Chuck Cartledge

    September 21, 2016 at 8:56am

    Contents

    1 Explanation 1

    2 Assignment 1

    3 What to submit 3

    A Sample files 3

    1 Explanation

    You will be creating an address book for an absent minded professor. This address book willserve as a basis for later programming assignments.

    The professor has a spotty memory, and only remembers parts of things. Things like:first name, middle name, last name, telephone numbers, and addresses. He remembers apart of each of these things, but not the whole thing.

    He needs a program that will read a comma separated file (where each line in the filecontains all the information he tracks), and then searches whichever selected field he thinkshe remembers for the text he enters.

    The program needs to print out any and all matches from the address book. He hasstarted the program, and needs you to finish it.

    2 Assignment

    These are the program requirements:

  • 1. Modify the attached interactive program to read the contents of the file:

    addressBook.tsv

    The file is attached and contains three silly contacts.

    2. Modify the program to:

    (a) Allow the professor to search any field. Using:

    A to search the address field,

    P to search the phone number field,

    M to search the middle name field,

    L to search the last name field.

    (He got the first name search pretty much done.)

    (b) Allow the professor to enter upper or lower case command letters.

    3. The program shall print to standard out. See the files section (see Section A) for allfiles. Remember, your output must go to standard out.

    4. The program should be properly documented (check the index for page references towhat constitutes good documentation).

    Because the professor is basically lazy, he will be using I/O redirection to test the pro-gram. The redirection will look like this:

    yourCompiledProgram < addressBook.cntrl 1>nul 2> resultFile

    diff resutltFile goldenFile

    It is the results of the diff command that will determine your grade.

    2

  • One of the common things about most modern operating systems (OSs) is their use of acommon set of values for file descriptors. File descriptors are used by the OS as indices intoa list of queues for processing I/O. When an application wants to do any I/O, the applicationgets a file descriptor from the OS and then uses that file descriptor as needed. The OS isresponsible for ensuring that the operation goes according to the application’s direction. Itis possible that the OS will not complete an action if the application crashes, or does notcleanly end its use of the file descriptor.A user can access the preset OS file descriptors outside the application. Here is a list ofnormal, preset file descriptors:

    Name Number unistd.h stdio.h iostreamStandard input 0 STDIN FILENO stdin cinStandard output 1 STDOUT FILENO stdout coutStandard error 2 STDERR FILENO stderr cerr

    About file descriptors

    Sometimes you’ll neither want, nor need to save the output from a program. Essentially,you’ll want to throw it away because it has no value. Most operating systems (OSs) havea special place, or syntax for “throwing things away.” An OS supports capturing outputfrom Standard Output, Standard Error file descriptors and then redirecting those outputs tosomewhere.Here are the special places where output can be redirected to and then lost by the OS:

    OS PlaceWindows nul*nix /dev/null

    About throwing things away

    3 What to submit

    The C++ source code that meets the assignment requirements.

    A Sample files

    This is a sample input files:

    • addressBook.cntrl

    3

    FElseFFirstp12FSomeFhopesQ

    "TCC Staff"

  • • addressBook.tsv

    • readAddressBook01.cpp

    4

    First Name,Middle Name,Last Name,(123)456-7890,5225 Figueroa Mountain Rd Los Olivos CA 93441Someone else,Eliza,Dreams,789-123-4567,Slaughterville OKSome close,To Eliza,Dreams,789-123-4567,Tulsa OK

    "TCC Staff"

    readAddressBook01.cpp

    #include

    #include

    bool readARecord(std::ifstream& in, std::string& fName, std::string& mName, std::string& lName, std::string& pNumber, std::string& addr);

    void printARecord(std::ostream& out, std::string fName, std::string mName, std::string lName, std::string pNumber, std::string addr);

    std::string normalizeText(std::string text);

    bool isTextInText(std::string lookIn, std::string lookFor);

    int main()

    {

      std::string fileName = "addressBook.tsv";

      std::string command;

      std::string firstName;

      std::string middleName;

      std::string lastName;

      std::string phoneNumber;

      std::string address;

      std::string search;

      

      std::ifstream input;

      bool moreData = true;

      bool foundMatch;

      

      input.open(fileName.c_str());

      command = "";

      while (command != "Q")

        {

          std::cout  command;

          if (command == "Q")

        {

          break;

        }

          input.clear();

          input.seekg(0, std::ios::beg);

          

          switch (command.at(0))

        {

        case 'F':

          std::cout  search;

          search = normalizeText(search);

          moreData = true;

          foundMatch = false;

          while (moreData)

            {

              moreData = readARecord(input, firstName, middleName, lastName, phoneNumber, address);

              if (moreData == false)

            {

              break;

            }

              if (isTextInText(normalizeText(firstName), search) == true)

            {

              std::cout 

  • 1/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    CSC-201 - Computer Science ILecture #5: Chapter 7

    Dr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck CartledgeDr. Chuck Cartledge

    September 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10amSeptember 21, 2016 at 9:10am

  • 2/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Table of contents I

    1 Test Results

    2 Schedule

    3 Miscellanea

    4 Control Structs.

    5 Add’l Oper’s

    6 Break

    7 Hands on

    8 Q & A

    9 Conclusion

    10 References

    11 Files

  • 3/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Histograms

    Histogram of questions and misses

  • 4/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Histograms

    Histogram of letter grades

    Test scores are only part of your final grade. See syllabus.

  • 5/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Histograms

    Q & A time.

    “’The Answer to the GreatQuestion . . . Of Life, the Universeand Everything . . . is. . . forty-two,’ said DeepThought, with infinite majestyand calm.”Douglas Adams, TheHitchhiker’s Guide to theGalaxy

  • 6/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Schedule for the semester

    Wk. Date Topic Wk. Date Topic1 08/22 Chaps. 1 – 2 X 9 10/17 Chap. 102 08/29 Chaps. 3 – 4 X 10 10/24 Chaps. 10 – 113 09/05 Chap. 5 X 11 10/31 Chaps. 10 – 114 09/12 Test – Chap. 6 X 12 11/07 Test– Chap. 145 09/19 Chap. 7 13 11/14 Chap. 146 09/26 Chap. 8 14 11/28 Chap. 187 10/03 Chap. 9 15 12/05 Chap. 188 10/10 Test – Chap. 10 16 12/12 Exam

  • 7/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Programming assignment #003

    File Based Address Book

    Objectives are fairly straightforward:

    Accept commands from the user

    Read strings from a data file

    Search strings for data from user

    Output strings to the screen in aparticular format, or outputmessage

    Submit your source code.

    This is a single person effort (not ateam effort).

    Due by start of class 4 Oct. 2016.

  • 8/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Corrections and additions since last lecture.

    Graded, and re-graded thetest

    Check syllabus to see howgrades are computed

    Homework for chapter 6 duebefore class

    Exchanged e-mails and hadoffice hours (videoconference)

  • 9/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    This and that

    Read from a file.

    Objectives are fairly straightforward:

    Read strings from a data file.

    First string is the key.

    Second string is the plain text.

    Output plain and “encrypted”strings to the screen in a particularorder

    Submit your source code.

    This is a single person effort (not ateam effort).

    Any questions or problems?

  • 10/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    Flow of control

    There are limited number of different “flow of control”

    Sequential – instructions are executed in order

    Function calls – program execution is transferred to a functionand then returned (with or without a return value)

    Selection – some instructions are executed, but others are not

    Looping – a set of instructions is executed more than once

  • 11/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    The “if” statement.

    The “if” statement, evaluates a conditional as “true” or“false”When the conditional is “true” then the next statement isexecuted.The conditional can be simple or complex.

    Examples of “if” statements:if ( true ) cout

  • 12/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    What if we want to execute more than one statement?

    We look at what defines a statement.

    if ( true ) cout

  • 13/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    Basic looping structures

    while loopwhile ( conditional) { statements with changer}for loopfor (initial; conditional; changer) { statements}do ...while loopdo { statements with changer} while (conditional)Handcrafted (which we won’t go into)

  • 14/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    The “infinite” loop

    There may be times when you want a loop to repeat, but theterminate conditions are too hard to make into a set ofcomparisons.std::string fileName = "/tmp/temp.txt";

    std::ifstream inputFile;

    int data = 0;

    inputFile.open(fileName.c_str());

    for (; ;) {

    data

  • 15/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    What if there is more than one “other” case

    The “if” statement handles exactly one conditional and thenexecutes code based on whether that conditional is “true” or“false”“if” statements can be nested to create very complex conditionalexpressions.But how can we efficiently handle many conditionals at once?Enter the “switch” statement. The “switch” statementcompares one expression against a number of conditions andexecutes code when the condition is true. We’ll play with the

    if.cpp and switch.cpp programs.

  • 16/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    Notional “switch” structure structure

    The “switch statement is aselection control structure formulti-way branching.

    IntegralExpression – anyexpression that can bereduced to an integer value

    case Constant# – anyconstant value that is thesame type as theIntegralExpression

    default – the “case” whenno other cases match

    Image from [2].

  • 17/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    Same image.

    Image from [2].

  • 18/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    Example of a “switch” statement

    cin >> letter >> first >> second;

    switch (letter)

    {

    case ’A’ :

    answer = (first + second);

    cout

  • 19/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    More details about the switch statement

    The value ofIntegralExpression (of char,short, int, long or enumtype) determines whichbranch is executed

    Case labels are constantintegral expressions

    Several case labels canprecede a statement

    Control branches to thestatement following thecase label that matches the

    value of IntegralExpression

    Control proceeds throughall remaining statements,including the default,unless redirected with break

    If no case label matches thevalue of IntegralExpression,control branches to thedefault label, if present

    Otherwise control passes tothe statement following theentire switch statement

    Forgetting to use break can cause logical errors

  • 20/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Things from the past

    Misc. things about break and continue statements

    A break statement can beused in switch or any ofthe 3 looping structures

    It causes an immediateexit from the currentstructure

    If used in a nestedstructure, it only exitsthe current structure

    A continue statement canonly be used in a loopingstructure

    It terminates the currentiteration, but not theentire loopIn a “for” loop, theupdate is still doneIn a “do – while” theexit condition is tested

    Indiscriminate use of break and continue can lead to confusingcode.

  • 21/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    More about C++ operators

    C++ operators we will know and love.

    There are a lot of declaredoperators in C++. Over the nextfew months will will learn aboutthe ones in red, and possibly theones in green.

    Image from [1].

  • 22/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    More about C++ operators

    Same image.

    Image from [1].

  • 23/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    More about C++ operators

    With so many operators, which has precedence?

    Not all operations are left toright. Precedence can be affectedby using parenthesis.

    Image from [3].

  • 24/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    More about C++ operators

    Same image.

    Image from [3].

  • 25/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    More about C++ operators

    With so many operators, which has precedence?

    Not all operations are left toright. Precedence can be affectedby using parenthesis.

    Image from [3].

  • 26/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    More about C++ operators

    Same image.

    Image from [3].

  • 27/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    More about C++ operators

    Specialized C++ operators

    What do these expressions do and why?

    Interesting expressions:23;2 * (alpha + beta);delta = 2 * 12;

    Confusing expressions:

    int1 = 14; int2 =++int1;

    int1 = 14; int2 =int1++;

    When in doubt, fire up CodeBlocks and test them out.

  • 28/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    fragile

    Bit operators

    What do these fragments produce, and why?

    When in doubt, fire up CodeBlocks and test them out.

  • 29/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    fragile

    What if we don’t like the type of our variable?

    There may be some cases where we want the compiler to changethe “type” of our data.This is known as “casting” the variable. It really is changing thevalue of the variable to the desired type.

    Functional notationintVar = int(floatVar);

    Prefix notationintVar = (int) floatVar;

    Keyword notationintVar = static cast(floatVar);

    Keyword notation is gaining popularity because it is easy to locatein multiple files.

  • 30/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    fragile

    What are the mechanics behind “casting” values?

    There are only two cases:

    If there is only one data type involved

    Trivial case: nothing happens

    If there is more than one data type involved

    Each data type is promoted to the next higher data type,until we have a trivial case.Order of data type promotion: int, unsigned int. long,float, double, long double

    Casting also happens behind the scenes with conditionals. Bestadvice is to compare like types.

  • 31/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    fragile

    A special C++ operator?

    This type of logic happens a lot:

    if (someConditional)

    c = something;

    else

    c = somethingElse;

    If fact it is so common in the C/C++ world, that it was added tothe language. It looks like this:

    c = (someConditional) ? something : somethingElse;

    Reduces likelihood of typing errors

  • 32/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Break time.

    Take about 10 minutes.

  • 33/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Practice exercises

    Programs to load into CodeBlocks and get running:

    1 if.cpp (look at and understand how nested sequential “ifs”work)

    2 switch.cpp (expand the program to print the first stanza whena 0 is entered)

    3 switches.cpp (expand to support multiple case labels, orsomething else)

    Others, if you have time.

  • 34/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Q & A time.

    “’The Answer to the GreatQuestion . . . Of Life, the Universeand Everything . . . is. . . forty-two,’ said DeepThought, with infinite majestyand calm.”Douglas Adams, TheHitchhiker’s Guide to theGalaxy

  • 35/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    What have we covered?

    Returned and discussed test #01Covered looping statements indifferent formsTalked about low level C++operatorsTalked about changing the type ofvariables (casting)Chapter 7 homework before class

    Next time: Chapter 8

  • 36/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    References I

    [1] Richard Smith et al., Working draft, standard for programminglanguage c++, ISO/IEC JTC1/SC22/WG21 document N4296 (2015).

    [2] Sylvia Sorkin, Programming and problem solving with c++,Teacher Resource Jones and Barlett Learning, 2014.

    [3] C++ Staff, C++ operator precedence,http://en.cppreference.com/w/cpp/language/

    operator_precedence, 2016.

    http://en.cppreference.com/w/cpp/language/operator_precedence

    http://en.cppreference.com/w/cpp/language/operator_precedence

  • 37/37

    Test Results Schedule Miscellanea Control Structs. Add’l Oper’s Break Hands on Q & A Conclusion References Files

    Files of interest

    1 if.cpp (just to start)

    2 switch.cpp (to expand)

    3 switches.cpp (to expand)

    4 Programming assignment #003

    if.cpp

    #include

    using namespace std;

    int main()

    {

      int inputInt;

      

      cout  inputInt;

      cout 

  • CSC-201 Fall 2016Assignment #3: File Based Address Book

    Due: Oct. 4, 2016

    Dr. Chuck Cartledge

    September 21, 2016 at 8:56am

    Contents

    1 Explanation 1

    2 Assignment 1

    3 What to submit 3

    A Sample files 3

    1 Explanation

    You will be creating an address book for an absent minded professor. This address book willserve as a basis for later programming assignments.

    The professor has a spotty memory, and only remembers parts of things. Things like:first name, middle name, last name, telephone numbers, and addresses. He remembers apart of each of these things, but not the whole thing.

    He needs a program that will read a comma separated file (where each line in the filecontains all the information he tracks), and then searches whichever selected field he thinkshe remembers for the text he enters.

    The program needs to print out any and all matches from the address book. He hasstarted the program, and needs you to finish it.

    2 Assignment

    These are the program requirements:

  • 1. Modify the attached interactive program to read the contents of the file:

    addressBook.tsv

    The file is attached and contains three silly contacts.

    2. Modify the program to:

    (a) Allow the professor to search any field. Using:

    A to search the address field,

    P to search the phone number field,

    M to search the middle name field,

    L to search the last name field.

    (He got the first name search pretty much done.)

    (b) Allow the professor to enter upper or lower case command letters.

    3. The program shall print to standard out. See the files section (see Section A) for allfiles. Remember, your output must go to standard out.

    4. The program should be properly documented (check the index for page references towhat constitutes good documentation).

    Because the professor is basically lazy, he will be using I/O redirection to test the pro-gram. The redirection will look like this:

    yourCompiledProgram < addressBook.cntrl 1>nul 2> resultFile

    diff resutltFile goldenFile

    It is the results of the diff command that will determine your grade.

    2

  • One of the common things about most modern operating systems (OSs) is their use of acommon set of values for file descriptors. File descriptors are used by the OS as indices intoa list of queues for processing I/O. When an application wants to do any I/O, the applicationgets a file descriptor from the OS and then uses that file descriptor as needed. The OS isresponsible for ensuring that the operation goes according to the application’s direction. Itis possible that the OS will not complete an action if the application crashes, or does notcleanly end its use of the file descriptor.A user can access the preset OS file descriptors outside the application. Here is a list ofnormal, preset file descriptors:

    Name Number unistd.h stdio.h iostreamStandard input 0 STDIN FILENO stdin cinStandard output 1 STDOUT FILENO stdout coutStandard error 2 STDERR FILENO stderr cerr

    About file descriptors

    Sometimes you’ll neither want, nor need to save the output from a program. Essentially,you’ll want to throw it away because it has no value. Most operating systems (OSs) havea special place, or syntax for “throwing things away.” An OS supports capturing outputfrom Standard Output, Standard Error file descriptors and then redirecting those outputs tosomewhere.Here are the special places where output can be redirected to and then lost by the OS:

    OS PlaceWindows nul*nix /dev/null

    About throwing things away

    3 What to submit

    The C++ source code that meets the assignment requirements.

    A Sample files

    This is a sample input files:

    • addressBook.cntrl

    3

    FElseFFirstp12FSomeFhopesQ

    "TCC Staff"

  • • addressBook.tsv

    • readAddressBook01.cpp

    4

    First Name,Middle Name,Last Name,(123)456-7890,5225 Figueroa Mountain Rd Los Olivos CA 93441Someone else,Eliza,Dreams,789-123-4567,Slaughterville OKSome close,To Eliza,Dreams,789-123-4567,Tulsa OK

    "TCC Staff"

    readAddressBook01.cpp

    #include

    #include

    bool readARecord(std::ifstream& in, std::string& fName, std::string& mName, std::string& lName, std::string& pNumber, std::string& addr);

    void printARecord(std::ostream& out, std::string fName, std::string mName, std::string lName, std::string pNumber, std::string addr);

    std::string normalizeText(std::string text);

    bool isTextInText(std::string lookIn, std::string lookFor);

    int main()

    {

      std::string fileName = "addressBook.tsv";

      std::string command;

      std::string firstName;

      std::string middleName;

      std::string lastName;

      std::string phoneNumber;

      std::string address;

      std::string search;

      

      std::ifstream input;

      bool moreData = true;

      bool foundMatch;

      

      input.open(fileName.c_str());

      command = "";

      while (command != "Q")

        {

          std::cout  command;

          if (command == "Q")

        {

          break;

        }

          input.clear();

          input.seekg(0, std::ios::beg);

          

          switch (command.at(0))

        {

        case 'F':

          std::cout  search;

          search = normalizeText(search);

          moreData = true;

          foundMatch = false;

          while (moreData)

            {

              moreData = readARecord(input, firstName, middleName, lastName, phoneNumber, address);

              if (moreData == false)

            {

              break;

            }

              if (isTextInText(normalizeText(firstName), search) == true)

            {

              std::cout