C++ Basics Cs246, Fall 2020

Total Page:16

File Type:pdf, Size:1020Kb

C++ Basics Cs246, Fall 2020 ASSIGNMENT #2: C++ BASICS CS246, FALL 2020 Assignment #2: C++ basics Due Date 1: Wednesday, October 7, 2020, 5:00 pm Due Date 2: Wednesday, October 21, 2020, 5:00 pm Online Quiz: Wednesday, October 28, 2020, 5:00 pm Topics that must have been completed before starting Due Date 1: 1. Software Testing 2. produceOutputs and runSuite from A1 Topics that must have been completed before starting Due Date 2: 1. C++: Introduction to C++ 2. Preprocessing and Compilation Learning objectives: • C++ I/O (standard, file streams) and output formatting • argv and argc • C++ strings and stringstreams • separate compilation and Makefiles • Questions 1a, 2a, and 3a are due on Due Date 1; questions 1b, 2b, 3b, 4b, 5 and 6 are due on Due Date 2. You must submit the online quiz on Learn by the Quiz date. • On this and subsequent assignments, you will take responsibility for your own testing. This assignment is designed to get you into the habit of thinking about testing before you start writing your program. If you look at the deliverables and their due dates, you will notice that there is no C++ code due on Due Date 1. Instead, you will be asked to submit test suites for C++ programs that you will later submit by Due Date 2. Test suites will be in a format compatible with that of the latter questions of Assignment 1, so if you did a good job writing your runSuite script, that experience will serve you well here. • Design your test suites with care; they are your primary tool for verifying the correctness of your code. Note that test suite submission zip files are restricted to contain a maximum of 40 tests. The size of each input (.in) file is also restricted to 300 bytes, and each output file (.out) is restricted to 1,000 bytes. This is to encourage you not to combine all of your testing eggs in one basket. • You must use the standard C++ I/O streaming and memory management (MM) facilities on this assignment; you may not use C-style I/O or MM. More concretely, you may #include the following C++ libraries (and no others!) for the current assignment: iostream, fstream, sstream, iomanip, and string. Marmoset will be setup to reject submissions that use C-style I/O or MM, or libraries other than the ones specified above. • We will manually check that you follow a reasonable standard of documentation and style, and to ver- ify any assignment requirements that are not automatically enforced by Marmoset. Code to a standard that you would expect from someone else if you had to maintain their code. Further comments on cod- ing guidelines can be found here: https://www.student.cs.uwaterloo.ca/˜cs246/F20/ codingguidelines.shtml • We have provided some code and sample executables in the subdirectory codeForStudents under the appropriate subdirectories. These executables have been compiled in the CS student environment and will not run anywhere else. Page 1 of 6 ASSIGNMENT #2: C++ BASICS CS246, FALL 2020 • You may not ask public questions on Piazza about what the programs that make up the assignment are supposed to do. A major part of this assignment involves designing test cases, and questions that ask what the programs should do in one case or another will give away potential test cases to the rest of the class. Questions found in violation of this rule will be marked private or deleted; repeat offences could be subject to discipline. Coding Assessment Questions 1 to 4 are part of the coding assessment, and may be publicly discussed on Piazza so long as solutions are neither discussed nor revealed. Question 1 (40% of DD1; 15% of DD2) In this question, you will write a C++ program called lineWrap, whose command-line syntax looks like this:1 lineWrap [-n maxLineLength] [-c censorWord] [inputFile] This program reads in lines of text, and prints them to cout, with at most maxLineLength characters in each printed line, and any remaining text printed afterwards (to a maximum of of maxLineLength again). The default value of maxLineLength is 20, but this can be overridden at the command-line, as we’ll see below. Note that you should preserve all white space in the input, except for the newline characters. For example, if the input file looks like this (here, we’ll use a period instead of actual spaces, to make them more obvious): a234567890b234567890c234567890d234567890e234567890 slings...and. .....arrows...of...outrageous then we expect the output file to look like this: a234567890b234567890 c234567890d234567890 e234567890 slings...and. .....arrows...of...o utrageous Note that the first line of input was 50 characters long, so we had to use three lines of output to print it all; the second input line was 13 characters long, so it fit onto one line of output. You can choose to override the maxLineLength by using the -n option at the command-line; this value must be a positive integer. The program can optionally take a censorWord (a string) as an argument; if one is specified on the command-line, then the censorWord must not appear in the output stream. The removal should be done before you try to print the line, so the output will line up as if the censorWord had never been in the input file in the first place. For example, consider this input file: a23456789gong0b234567890gonggongc234567890d234567890e234567890 ..gong..gogongng.. If there is no censorWord given, then the output should be this a23456789gong0b23456 7890gonggongc2345678 90d234567890e2345678 90 ..gong..gogongng.. 1Note that as per UNIX convention, items in square brackets are optional; if you can call lineWrap with no arguments, it will take input from cin. Page 2 of 6 ASSIGNMENT #2: C++ BASICS CS246, FALL 2020 But if the censorWord is set to gong, then the output should be this. a234567890b234567890 c234567890d234567890 e234567890 ...... The processing of the second line of input shows that (a) whitespace around a censorWord is preserved in the output and (b) if deleting one instance of the censorWord creates another instance of the censorWord, you have to delete that second instance (and third and fourth ...) also. That is, gogongng becomes gong after deleting the gong in the middle, but we’re not done yet; we have to keep deleting the censorWord until no instances remain. If the censorWord is the empty string "", then no censoring should be done; note that a good design may be able to implement this case without any special handling. If an input file name is specified on the command-line, then the input text should be taken from there; otherwise, assume that the input text will come from cin. You need to perform error checking on the command-line arguments: • If the -n option is used, it must be followed by a positive integer. • If the -c option is used, it must be followed by another string i.e., lineWrap -c on its own is illegal. • If an input file name is specified, you must be able to create an istream object successully using that name. Use the following global definitions for error messages:2 const string eBadLineLength = "Error, maxLineLength must be a positive integer"; const string eNoCensorWord = "Error, missing censor word"; const string eCantOpenInputFile = "Error, could not open input file"; If one of these errors arises, print the appropriate message to cerr with nothing else on the line and abort via exit(1). Note that your program should be able to process valid command-line calls with options in any order. That is, the following should all be legal and have the same output: $ lineWrap -n 15 -c gong test1.txt $ lineWrap -c gong test1.txt -n 15 $ lineWrap test1.txt -n 15 -c gong You may assume without having to check that each command-line argument is used at most once; so we don’t care about the output to this, for example: $ lineWrap -c gong test1.txt -n 15 -c fluble -n 35 Feel free to use any element of the C++ APIs for string (http://www.cplusplus.com/reference/string/ string/) and stringstream (http://www.cplusplus.com/reference/sstream/?kw=sstream), even if it has not been discussed “in lecture”; in particular, string::npos might be useful to you. Hint: Try creating the basic program without the command-line options first, then progressively add in the command-line features once you are confident you have solved the simpler problem. a) Due on Due Date 1: Design a test suite for this program. Call your suite file suiteq1.txt. Zip your suite file, together with the associated .in, .out, and .args files, into the file a2q1.zip. Since the .in extension is used for file redirection, and .args is for command-line arguments, the input test files you create should not use either of those extensions. b) Due on Due Date 2: Write the program in C++. Save your solution in a file named a2q1.cc. 2These definitions will also be provided to you in the a2/codeForStudents/q1 subdirectory of the course git repository; please use that file rather than copy/pasting from this PDF to avoid strange formatting errors. Page 3 of 6 ASSIGNMENT #2: C++ BASICS CS246, FALL 2020 Question 2 (30% of DD1; 10% of DD2) You are going to write a slightly simplified version of the GNU UNIX utilities basename in C++; we expect that you will make effective use of the C++ string API in doing so. Basically, basename takes a valid UNIX pathname such as /usr/bin/vim and returns the name of the file with the enclosing directory names removed. For example, $ basename /usr/bin/vim vim More precisely3, given a PATHNAME: basename outputs PATHNAME with any leading directory components removed.
Recommended publications
  • Configuring UNIX-Specific Settings: Creating Symbolic Links : Snap
    Configuring UNIX-specific settings: Creating symbolic links Snap Creator Framework NetApp September 23, 2021 This PDF was generated from https://docs.netapp.com/us-en/snap-creator- framework/installation/task_creating_symbolic_links_for_domino_plug_in_on_linux_and_solaris_hosts.ht ml on September 23, 2021. Always check docs.netapp.com for the latest. Table of Contents Configuring UNIX-specific settings: Creating symbolic links . 1 Creating symbolic links for the Domino plug-in on Linux and Solaris hosts. 1 Creating symbolic links for the Domino plug-in on AIX hosts. 2 Configuring UNIX-specific settings: Creating symbolic links If you are going to install the Snap Creator Agent on a UNIX operating system (AIX, Linux, and Solaris), for the IBM Domino plug-in to work properly, three symbolic links (symlinks) must be created to link to Domino’s shared object files. Installation procedures vary slightly depending on the operating system. Refer to the appropriate procedure for your operating system. Domino does not support the HP-UX operating system. Creating symbolic links for the Domino plug-in on Linux and Solaris hosts You need to perform this procedure if you want to create symbolic links for the Domino plug-in on Linux and Solaris hosts. You should not copy and paste commands directly from this document; errors (such as incorrectly transferred characters caused by line breaks and hard returns) might result. Copy and paste the commands into a text editor, verify the commands, and then enter them in the CLI console. The paths provided in the following steps refer to the 32-bit systems; 64-bit systems must create simlinks to /usr/lib64 instead of /usr/lib.
    [Show full text]
  • CS101 Lecture 9
    How do you copy/move/rename/remove files? How do you create a directory ? What is redirection and piping? Readings: See CCSO’s Unix pages and 9-2 cp option file1 file2 First Version cp file1 file2 file3 … dirname Second Version This is one version of the cp command. file2 is created and the contents of file1 are copied into file2. If file2 already exits, it This version copies the files file1, file2, file3,… into the directory will be replaced with a new one. dirname. where option is -i Protects you from overwriting an existing file by asking you for a yes or no before it copies a file with an existing name. -r Can be used to copy directories and all their contents into a new directory 9-3 9-4 cs101 jsmith cs101 jsmith pwd data data mp1 pwd mp1 {FILES: mp1_data.m, mp1.m } {FILES: mp1_data.m, mp1.m } Copy the file named mp1_data.m from the cs101/data Copy the file named mp1_data.m from the cs101/data directory into the pwd. directory into the mp1 directory. > cp ~cs101/data/mp1_data.m . > cp ~cs101/data/mp1_data.m mp1 The (.) dot means “here”, that is, your pwd. 9-5 The (.) dot means “here”, that is, your pwd. 9-6 Example: To create a new directory named “temp” and to copy mv option file1 file2 First Version the contents of an existing directory named mp1 into temp, This is one version of the mv command. file1 is renamed file2. where option is -i Protects you from overwriting an existing file by asking you > cp -r mp1 temp for a yes or no before it copies a file with an existing name.
    [Show full text]
  • Humidity Definitions
    ROTRONIC TECHNICAL NOTE Humidity Definitions 1 Relative humidity Table of Contents Relative humidity is the ratio of two pressures: %RH = 100 x p/ps where p is 1 Relative humidity the actual partial pressure of the water vapor present in the ambient and ps 2 Dew point / Frost the saturation pressure of water at the temperature of the ambient. point temperature Relative humidity sensors are usually calibrated at normal room temper - 3 Wet bulb ature (above freezing). Consequently, it generally accepted that this type of sensor indicates relative humidity with respect to water at all temperatures temperature (including below freezing). 4 Vapor concentration Ice produces a lower vapor pressure than liquid water. Therefore, when 5 Specific humidity ice is present, saturation occurs at a relative humidity of less than 100 %. 6 Enthalpy For instance, a humidity reading of 75 %RH at a temperature of -30°C corre - 7 Mixing ratio sponds to saturation above ice. by weight 2 Dew point / Frost point temperature The dew point temperature of moist air at the temperature T, pressure P b and mixing ratio r is the temperature to which air must be cooled in order to be saturated with respect to water (liquid). The frost point temperature of moist air at temperature T, pressure P b and mixing ratio r is the temperature to which air must be cooled in order to be saturated with respect to ice. Magnus Formula for dew point (over water): Td = (243.12 x ln (pw/611.2)) / (17.62 - ln (pw/611.2)) Frost point (over ice): Tf = (272.62 x ln (pi/611.2)) / (22.46 -
    [Show full text]
  • Common Commands Cheat Sheet by Mmorykan Via Cheatography.Com/89673/Cs/20411
    Common Commands Cheat Sheet by mmorykan via cheatography.com/89673/cs/20411/ Scripting Scripting (cont) GitHub bash filename - Runs script sleep value - Forces the script to wait value git clone <url​ > - Clones gitkeeper url Shebang - "#​ !bi​ n/b​ ash​ " - First line of bash seconds git add <fil​ ena​ me>​ - Adds the file to git script. Tells script what binary to use while [[ condition ]]; do stuff; done git commit - Commits all files to git ./file​ name - Also runs script if [[ condition ]]; do stuff; fi git push - Pushes all git files to host # - Creates a comment until [[ condition ]]; do stuff; done echo ${varia​ ble} - Prints variable words="​ h​ ouse dogs telephone dog" - Package / Networking hello_int = 1 - Treats "1​ " as a string Declares words array dnf upgrade - Updates system packages Use UPPERC​ ASE for constant variables for word in ${words} - traverses each dnf install - Installs package element in array Use lowerc​ ase​ _wi​ th_​ und​ ers​ cores for dnf search - Searches for package for counter in {1..10} - Loops 10 times regular variables dnf remove - Removes package for ((;;)) - Is infinite for loop echo $(( ${hello​ _int} + 1 )) - Treats hello_int systemctl start - Starts systemd service as an integer and prints 2 break - exits loop body systemctl stop - Stops systemd service mktemp - Creates temporary random file for ((count​ er=1; counter -le 10; counter​ ++)) systemctl restart - Restarts systemd service test - Denoted by "[[ condition ]]" tests the - Loops 10 times systemctl reload - Reloads systemd service condition
    [Show full text]
  • Cygwin User's Guide
    Cygwin User’s Guide Cygwin User’s Guide ii Copyright © Cygwin authors Permission is granted to make and distribute verbatim copies of this documentation provided the copyright notice and this per- mission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this documentation under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this documentation into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. Cygwin User’s Guide iii Contents 1 Cygwin Overview 1 1.1 What is it? . .1 1.2 Quick Start Guide for those more experienced with Windows . .1 1.3 Quick Start Guide for those more experienced with UNIX . .1 1.4 Are the Cygwin tools free software? . .2 1.5 A brief history of the Cygwin project . .2 1.6 Highlights of Cygwin Functionality . .3 1.6.1 Introduction . .3 1.6.2 Permissions and Security . .3 1.6.3 File Access . .3 1.6.4 Text Mode vs. Binary Mode . .4 1.6.5 ANSI C Library . .4 1.6.6 Process Creation . .5 1.6.6.1 Problems with process creation . .5 1.6.7 Signals . .6 1.6.8 Sockets . .6 1.6.9 Select . .7 1.7 What’s new and what changed in Cygwin . .7 1.7.1 What’s new and what changed in 3.2 .
    [Show full text]
  • Μmachine Definitions
    Machine/Code For the final part of the CS450 project, you are to complete a fully functional Pascal compiler. Since it would be impractical to have you generate assembly code for a real machine (with all the intricacies of the target machine), we have created a virtual machine that has been designed specifically for a Pascal compiler. The Machine (and is associated assembly language Code) greatly simplifies the task of code generation while still requiring you to handle many of the problems faced by other compiler writers. At this point in time, you should have written a scanner and parser for Pascal, should be working on the symbol table and should be thinking about semantic processing and code generation. The following information about the Machine and Code is provided to assist you in your design and implementation of the remaining parts of the Pascal compiler project: Machine Specification: The Machine is a virtual machine (simulated by a program) with the following hardware characteristics: Separate instruction space (for assembly code) and RAM (for data storage/retrieval) 10 general purpose registers (D0 - D9) Special stack pointer register (SP) The Machine is a stack-based machine; all memory is allocated/deallocated on the data stack residing in RAM: The data stack supports types: Integer, Float/Fixed, Strings. All data types have the same size of 1. The data stack grows upwards (starts at 0, pushes increment the SP, pops decrement the SP) Supported Data Types Integer: As defined in the Pascal tokens document. Size: 1. Float/Fixed: Numbers represented as floating point or fixed point are supported and have a size of 1.
    [Show full text]
  • Unix (And Linux)
    AWK....................................................................................................................................4 BC .....................................................................................................................................11 CHGRP .............................................................................................................................16 CHMOD.............................................................................................................................19 CHOWN ............................................................................................................................26 CP .....................................................................................................................................29 CRON................................................................................................................................34 CSH...................................................................................................................................36 CUT...................................................................................................................................71 DATE ................................................................................................................................75 DF .....................................................................................................................................79 DIFF ..................................................................................................................................84
    [Show full text]
  • Laboratory 1: Getting Familiar with GLUE UNIX Programming Environment
    Laboratory 1: Getting Familiar with GLUE UNIX Programming Environment Lecture notes: 1. Scope of the course Prerequisite for ENEE 150 (see the last page for more details), very basic skills in programming and UNIX. a. Principles of programming and software development. b. C will be used as the programming language to illustrate the concepts. c. Basic skills in UNIX operating systems. 2. How to program (or develop software package in the future) a. Document everything you do in each of the following steps. b. Understand the project/problem requirements c. Develop algorithm (the way or method to solve the problem) d. Plan for the implementation of your algorithm (data structure, etc.) e. Write the programming (C, C++, Java, Matlab, etc.) f. Compile the program (gcc or cc in GLUE UNIX for C codes. Compiler is the interpreter that translates the program written in the so-called high level programming languages like C by human, who call themselves programmers, and understandable by human to the low level language that the computer understands.) g. Execute, test, and debug your program on sample data. h. Go back to step d. (modify your code) if necessary (programming or syntax bugs). i. Go back to step c. or step b. if there are serious problems (algorithm or logic bugs). j. Confirm that all the project requirements are met. (output format, etc.) 3. What is UNIX? a. UNIX is an operating system, like windows, which is a complex set of computer codes that manages the activities and resources of the computer. It is very popular in universities and colleges.
    [Show full text]
  • ANSWERS ΤΟ EVEN-Numbered
    8 Answers to Even-numbered Exercises 2.1. WhatExplain the following unexpected are result: two ways you can execute a shell script when you do not have execute permission for the file containing the script? Can you execute a shell script if you do not have read permission for the file containing the script? You can give the name of the file containing the script as an argument to the shell (for example, bash scriptfile or tcsh scriptfile, where scriptfile is the name of the file containing the script). Under bash you can give the following command: $ . scriptfile Under both bash and tcsh you can use this command: $ source scriptfile Because the shell must read the commands from the file containing a shell script before it can execute the commands, you must have read permission for the file to execute a shell script. 4.3. AssumeWhat is the purpose ble? you have made the following assignment: $ person=zach Give the output of each of the following commands. a. echo $person zach b. echo '$person' $person c. echo "$person" zach 1 2 6.5. Assumengs. the /home/zach/grants/biblios and /home/zach/biblios directories exist. Specify Zach’s working directory after he executes each sequence of commands. Explain what happens in each case. a. $ pwd /home/zach/grants $ CDPATH=$(pwd) $ cd $ cd biblios After executing the preceding commands, Zach’s working directory is /home/zach/grants/biblios. When CDPATH is set and the working directory is not specified in CDPATH, cd searches the working directory only after it searches the directories specified by CDPATH.
    [Show full text]
  • Linux Cheat Sheet
    1 of 4 ########################################### # 1.1. File Commands. # Name: Bash CheatSheet # # # # A little overlook of the Bash basics # ls # lists your files # # ls -l # lists your files in 'long format' # Usage: A Helpful Guide # ls -a # lists all files, including hidden files # # ln -s <filename> <link> # creates symbolic link to file # Author: J. Le Coupanec # touch <filename> # creates or updates your file # Date: 2014/11/04 # cat > <filename> # places standard input into file # Edited: 2015/8/18 – Michael Stobb # more <filename> # shows the first part of a file (q to quit) ########################################### head <filename> # outputs the first 10 lines of file tail <filename> # outputs the last 10 lines of file (-f too) # 0. Shortcuts. emacs <filename> # lets you create and edit a file mv <filename1> <filename2> # moves a file cp <filename1> <filename2> # copies a file CTRL+A # move to beginning of line rm <filename> # removes a file CTRL+B # moves backward one character diff <filename1> <filename2> # compares files, and shows where differ CTRL+C # halts the current command wc <filename> # tells you how many lines, words there are CTRL+D # deletes one character backward or logs out of current session chmod -options <filename> # lets you change the permissions on files CTRL+E # moves to end of line gzip <filename> # compresses files CTRL+F # moves forward one character gunzip <filename> # uncompresses files compressed by gzip CTRL+G # aborts the current editing command and ring the terminal bell gzcat <filename> #
    [Show full text]
  • UNIX Logout ^D Or Exit Man Command Man -K Keyword Ls Ls -A Ls -L Ls -G Cp
    UNIX Reference Page 1 of 3 UNIX Reference Computing and Information Technology Basic Commands Log out of system logout Exit current shell ^D or exit Online Documentation See online manual page man command Search for a manual page man -k keyword Files List filenames ls - with hidden files ls -a - with file permissions ls -l - with group ownership ls -g Copy a file cp old new Copy a file to dirname cp file dirname Rename (move) a file mv old new Remove (delete) a file rm file Append file1 to file2 cat file1 >> file2 Home directory ~ Home directory of user ~user Change file permissions chmod (ugo +-rwx) file Wild cards - single character ? - multiple characters * - range (a and b are single [a-b] characters) File Editors Emacs emacs file vi vi file pico pico file Using less View file less file next line <Return> next page <Space> search for pattern /pattern next occurrence n next file :n help :h http://wings.buffalo.edu/computing/Documentation/unix/ref/unixref.html 9/13/2004 UNIX Reference Page 2 of 3 quit :q Directories Make a directory mkdir dirname Change directories cd dirname Remove a directory rmdir dirname See thecurrent directory name pwd Current directory . Parent of the current directory .. Root of the file system / Printing Print file to default printer lpr file (Bell 101) Print file to a printer at another lpr -Pprintername site file View printer queue lpq -Pprinter Remove job number jn lprm jn View job turnaround time prstat Job and Process Control Run job j in the background j& List jobs jobs Connect to job number n %n List
    [Show full text]
  • Operating Systems 06R
    Operating Systems 06r. Assignment 5 Discussion Paul Krzyzanowski Rutgers University Spring 2015 March 9, 2015 © 2014-2015 Paul Krzyzanowski 1 Assignment 5 • Write a simple shell – Read one line: command and arguments – Run the command with the given arguments – Wait for the command to exit – Print the exit code of the command • You need to support built-in commands – cd dirname Change the current working directory to dirname – exit value Exit the shell. Optionally specify a value for the exit code March 9, 2015 © 2014-2015 Paul Krzyzanowski 2 What you need to support • You need to support built-in commands – cd dirname Change the current working directory to dirname – exit value Exit the shell. Optionally specify a value for the exit code • You need to support pipes – Pipe: ability to redirect the output of one program to the input of another program March 9, 2015 © 2014-2015 Paul Krzyzanowski 3 You do not need to support • A command that spans multiple lines • Background processes • Environment variables • Multiple commands per line – E.g.: pwd; echo hello; ls /; who • Programming constructs – E.g., while, for, if, do • I/O redirection – E.g., ls -l >outfile • Any other constructs not specifically mentioned March 9, 2015 © 2014-2015 Paul Krzyzanowski 4 Understanding pipes • Guiding philosophy in the design of Unix commands and the Unix shell – A set of small, well-defined commands – Each command does one thing – The output of a command should ideally be in a format that is useful as the input to another command (avoid headers and other
    [Show full text]