Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Lab Exercise on Library Files and Function Calls in C++, Lab Reports of Computer Science

Instructions for a lab exercise where students practice using library files and making function calls to functions within libraries. It covers both system and user-created library files, preprocessor directives, and the use of standard library files such as cmath. The document also includes examples of function calls and the use of input and output streams.

Typology: Lab Reports

Pre 2010

Uploaded on 08/13/2009

koofers-user-t1o
koofers-user-t1o 🇺🇸

10 documents

1 / 7

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CS 220 Lab 3
Libraries, Function Calls, I/O and IO Manip
Due Monday
YOU WILL FIND IT USEFUL TO HAVE YOUR TEXTBOOK ON HAND WHILE
COMPLETING SOME PORTIONS OF THIS LAB. In this week’s lab, you’ll be practicing using
library files (both system and user created) and making function calls to functions within libraries.
Special emphasis will be placed on using I/O functions.
Before You Start
Create a subdirectory named 220 in your public_html directory.
Set the permissions so the contents are accessible by the web server running on paprika.
Copy the lab3 directory and the files contained in it into your file space using the command
cp –R ~ernie/220/lab3 $HOME/public_html/220/
The –R flag tells cp to copy the directory and all of the files contained within it into your specified
directory.
Now set the permissions so the directory lab3 is accessible by the web server. You'll put the answers to
the questions and other deliverables in this directory, so they can be viewed using a web browser.If, for
example, you put the answers to the questions in questions3.txt, and set the permissions correctly on that
file, and you substitute your login name for yourloginname in what follows, then it will be possible to
view the contents of that file using a Web browser and the URL
http://paprika.umw.edu/~yourloginname/220/lab3/questions3.txt
Now change the current directory to the one named lab3 mentioned above by entering
cd lab3
Verify you are in the correct directory by entering
pwd
Question #1. What does pwd do? For a synopsis take a look at the man page by entering man pwd.
Take a look at the names and sizes of the files in the directory by entering
ls -l
Remember, your personal file space is very limited to allow paprika to provide service to many users. As
a result, you will have to be diligent about cleaning up your own file space. The C++ compiler creates
very large executable files. Your directory space can only accommodate one or two executables at a time.
As a result, you should always delete .R files (or a.out files) as soon as you no longer need them. You’re
not really losing anything by deleting an executable because you can always recreate it by re-compiling
the source file. Keep all the source files that you create through the semester – these are small and do not
take much space. Delete all of the executable files that you create through the semester. If you forget to
remove an executable file, the system administrator will probably do it for you in the wee hours of the
morning. A program is run daily which searches for files called something.R (and a.out) and removes all
of those files from everyone’s directory.
Including Library Files
The file guess.cpp program contains the code for a program that allows a user to play a simple game. The
code for a function called random( ). Compile the program and test it a few times until you’re until
you’re comfortable with the way it works. We are also going to look at the program in the file
guess2.cpp. It has identical functionality but uses the random( ) function from a local library file (rather
than including the code within the program file).
1
pf3
pf4
pf5

Partial preview of the text

Download Lab Exercise on Library Files and Function Calls in C++ and more Lab Reports Computer Science in PDF only on Docsity!

CS 220 Lab 3 Libraries, Function Calls, I/O and IO Manip Due Monday YOU WILL FIND IT USEFUL TO HAVE YOUR TEXTBOOK ON HAND WHILE COMPLETING SOME PORTIONS OF THIS LAB. In this week’s lab, you’ll be practicing using library files (both system and user created) and making function calls to functions within libraries. Special emphasis will be placed on using I/O functions. Before You Start Create a subdirectory named 220 in your public_html directory. Set the permissions so the contents are accessible by the web server running on paprika. Copy the lab3 directory and the files contained in it into your file space using the command cp –R ~ernie/220/lab3 $HOME/public_html/220/ The –R flag tells cp to copy the directory and all of the files contained within it into your specified directory. Now set the permissions so the directory lab3 is accessible by the web server. You'll put the answers to the questions and other deliverables in this directory, so they can be viewed using a web browser.If, for example, you put the answers to the questions in questions3.txt , and set the permissions correctly on that file, and you substitute your login name for yourloginname in what follows, then it will be possible to view the contents of that file using a Web browser and the URL http://paprika.umw.edu/~yourloginname/220/lab3/questions3.txt Now change the current directory to the one named lab3 mentioned above by entering cd lab Verify you are in the correct directory by entering pwd Question #1. What does pwd do? For a synopsis take a look at the man page by entering man pwd. Take a look at the names and sizes of the files in the directory by entering ls -l Remember, your personal file space is very limited to allow paprika to provide service to many users. As a result, you will have to be diligent about cleaning up your own file space. The C++ compiler creates very large executable files. Your directory space can only accommodate one or two executables at a time. As a result, you should always delete .R files (or a.out files) as soon as you no longer need them. You’re not really losing anything by deleting an executable because you can always recreate it by re-compiling the source file. Keep all the source files that you create through the semester – these are small and do not take much space. Delete all of the executable files that you create through the semester. If you forget to remove an executable file, the system administrator will probably do it for you in the wee hours of the morning. A program is run daily which searches for files called something.R (and a.out ) and removes all of those files from everyone’s directory. Including Library Files The file guess.cpp program contains the code for a program that allows a user to play a simple game. The code for a function called random( ). Compile the program and test it a few times until you’re until you’re comfortable with the way it works. We are also going to look at the program in the file guess2.cpp. It has identical functionality but uses the random( ) function from a local library file (rather than including the code within the program file).

Preprocessor Directives and System Library Files The term library is often used to refer to any group of functions that might be used in more than one program. These functions usually perform common tasks. For example the iostream library contains cin and cout. When you want to use these operators, you write #include at the beginning of your program, as you have seen in earlier examples. This particular preprocessor directive (#include is one preprocessor directive) inserts the contents of the file iostream.h into your program at the point it is invoked. Using Local Library Files Open the file guess2.cpp. You will see that the main( ) function of this program is nearly identical to the program in guess.cpp. The primary difference is that the guess.cpp program contained a function called random( ) within the file; the guess2.cpp program calls a function called random( ) which is contained within a local library file. A local library file is a file that is not part of the standard C++ package, but which contains one or more useful functions. The library we will use in guess2.cpp is a file called random.h. Open random.h now (in vim or another editor). Notice that, in this case, there is only one function in the library. Now open the file guess2.cpp which contains the function main( ) (which you may recognize from guess.cpp in the previous lab). Note the statement #include “random.h” near the top of the file. The #include preprocessor directive is necessary so the compiler has access to the function prototype. You may notice that the #include statement contains the filename random.h delimited by quotation marks. This is because random.h is a local file. Any time the file to be included is a local file in your directory; use quotation marks to delimit the filename. When the header file is a standard library file (as is the case with iostream.h ), use angle brackets (< >) to delimit the filename. Preprocessor directives for standard libraries are the one of the few places that angle brackets appear in C++ code. Compile the program guess2.cpp. Run the resulting executable file guess2.R and convince yourself that it works. Question # 2: Write the preprocessor directive necessary for the compiler to have access to the prototypes in the standard library file called cmath.h. How would this preprocessor directive change if you wanted the compiler to have access to a user created library file call mathfunctions.h? Before moving on, delete the executable guess2.R. Remember that executable files are large and should always be deleted as soon as possible to free up your disk space. Using Standard Library Functions This week you’ll practice using functions found in system library files. The ideas for using system libraries are the same as those for using user defined libraries (also called local libraries): you’ll need to include the appropriate library files in your program, the library will contain various function definitions, and you will need to know information about the name, return type, and expected parameters for any function that you wish to invoke. The extra challenge with system library files is that you don’t have easy access to the system library files and therefore cannot view the functions or comments. Instead, you must refer to a C++ reference about standard libraries. One is provided in Appendix C of your textbook. Suppose we want to find the square root of 1024. We can use the sqrt( ) function from the standard math library (called the cmath library). Refer to page 1016-1018 in your textbook where you will see information about all function associated with the cmath library listed. The sqrt( ) function has the following prototype: double sqrt(double);

Why wasn’t the compilation successful? Take a closer look at the cin and cout statements in the program. We use extraction operators and insertion operators with these streams to get and put information. The extraction operator ( >> ) should be used with cin to get information from the input stream (i.e. we want information to be taken from the keyboard into the variable yourName ). Correspondingly, the insertion operator ( << ) should be used with cout to put information to the output stream (the screen). It makes no sense to put information to an input stream or get information from an output stream. It is helpful to think of the operators, as arrows pointing in the direction information should flow. Change each >> to << in the cout statements and each << to >> in the cin statements. Compile the program again to ensure that all corrections have been made. Stream Functions In addition to the “get” and “put” operators, streams provide a group of functions with which you can manipulate data. To introduce some of these, we will continue working with the hello.cpp program you already opened. After the declaration of yourName , add the lines char first; char middle; char last; // variables to hold initials // prompt the user for the three initials cout << “Enter your initials (first, middle, last)”; cin >> first >> middle >> last; Also change the line with “How are you today?” to instead read cout << “Your initials are “ << first << ‘ ‘ << middle << ‘ ‘ << last << endl; Now compile the program as before and then execute it. When prompted for input, type exactly as follows where [space] means press the space key: J [space] E [space] S [space] Joe [Enter] Note the output. Okay, now run the program again, this time entering for input JES [Enter] Joe [Enter] Note that the output is the same in both cases, even though we have spaces between the initials in the first case. This is due to the fact that using >> in conjunction with cin will ignore white space (i.e. spaces, tabs, returns). In the first case, the program reads each of the three characters as if there were no spaces at all. Now delete the cin statement that reads the initials and replace it with the following three lines: cin.get(first); cin.get(middle); cin.get(last); We have added the function get() , which is coupled with the input stream, to input the initials. To use such a stream function, give the stream variable name followed by a period, and finally the function name and parameters. Note that the parameter to the get( ) function must be of type char , and that only a single character is read from input.

Question #4: Why is the following statement invalid in this context? get(first); Now compile and execute the program again, giving the first case of input from before. The output should not be as expected. Question #5: What is the output in this case? Again execute the program, giving the second case of input from before. You should now see the expected output. At this point, you should be asking yourself: what is the difference? As mentioned before, get( ) reads only one character from input. Unlike >>, however, it does not ignore white space. For the first case of input, the program reads the first space instead of skipping over it. The sequence of characters the program actually reads for the first case of input looks like J E S \n J o e \n And for the second case of input Where \n is the newline, or return character. From this picture, it should be clear that spaces, newlines, tabs, etc. are valid characters just like any other part of the input and should be dully noted. This unfortunate circumstance can be overcome by using another of the C++ functions provided with streams. Add the following line twice to the program, once before and once after the middle initial is read: cin.ignore(10, ‘ ‘); Compile and execute the program again, giving the first case of input as before. The output should now be the same as the other expected cases. Now let’s understand why the previous additions alleviated the problem. The ignore( ) function above instructs cin to either skip the next ten input characters, or skip characters until a space is encountered. Since we put an ignore() before the second and third initials were read, cin discarded the spaces and read the initials as desired. The numeric parameter given to ignore() can be any number, and the delimiter parameter can be any character to skip to (return, tab, space or even a standard character). Once you have made the previous changes and answered all the questions, save the program. Remove the executable hello.R. Function Prototypes and Function Calls Function implementations are not always found in library files. Sometime you will write functions that are useful specifically for the application that you’re working on. In these cases, you will include the function implementation in the program file rather than in a library. In most programs that we will work with in this course, you will see function prototypes at the top of file. These prototypes tell the compiler (and you) important information about the function. Specifically, you can identify the number of parameters that the function takes, the data type of each parameter, and also the return type of the function. You can then use this information to make calls to functions using appropriate variables or literals. If the function and parameters have meaningful identifiers associated with them, you do not need to understand the underlying operations performed in a function in order to use the function within a program. J E S \n J o e \n

Circle Circum(ft) Cost of Material 1 Cost of Material 2 Area A 80.11 476.66 793.10 510. B 103.67 616.85 1026.36 855. C 38.48 228.98 381.00 117.  When printing the cost of using each material, multiply the appropriate price by the circumference of the appropriate circle.  The width of each column is given in the code that outputs the table headers. Note that the first column is left justified, while all others are right justified.  Don’t forget to personalize your program header comments appropriately. After you have completed the program, compile the source file. Correct any syntax errors produced during compilation. Then execute the program. Use the following input:

33

Verify that the output matches the sample output in the table above. Create a typescript of your program output by typing script garden.R exit Summary of Formatting Commands Format Command Floating point precision cout.setf(ios::fixed, ios::floatfield); cout.precision(number_decimals); cout << variableName; Left justify cout.setf(ios::left, ios::adjustfield); cout << variableName; Right justify cout.setf(ios::right, ios::adjustfield); cout << variableName; Column width cout << setw(number_spaces) << variableName; Put links on your Lab Web page  To the answers to the 6 questions in one file  To the file functions.cpp  To the file hello.cpp  To the file garden.cpp  To the typescript file