Objectives:
Introduction
This lab reviews some of what you already know about C++ programming
and adds new details. In particular, you will learn how to input
data from the keyboard, sometimes known as the standard input device,
using the file stream named cin. You will learn more about the string,
float and int data types, including how to use some powerful functions
that are available in standard libraries. Most of these are functions
that work like functions in mathematics -- you send the function an argument
and it returns a value. However, you will see one example of a "void"
function, one that does a job without returning a value. Finally,
you will learn a bit about how to make C++ output "pretty."
Data input
The file cla4a.cpp contains a short C++ program to calculate the area
of a rectangle. Specifically, it inputs the length and width of the
rectangle from the keyboard.
cp $CLA/cla4a.cpp cla4a.cpp
Display cla4a.cpp on your screen. The first variable declared in cla4a.cpp is length; it has type float.cin >> length;inputs a value for length from the keyboard. Here cin is the name for the standard input stream (keyboard) and the extraction operator >> "inputs to" the destination. When executed, the statement accepts characters from the keyboard until Enter is depressed. Assuming these characters represent a valid float value, then that value is stored in the variable length.
The output statement
cout << "Enter length of rectangle: ";just before the input statement is very important. Without it, the user would not know that the computer was expecting data to be entered, and might think the computer had just "crashed." You should almost always use an output statement to "prompt" for data to be entered from the keyboard.
Look at the form of this output statement. It does not
have an endl manipulator at the end
of it. This is so that the cursor stays on the same line with the
prompt. The string to be displayed ends with a space to put a little
separation between the colon (:) and the cursor. This makes the screen
easier to read. Good programmers pay attention to user-friendly details!
Exercise 2:
In cla4a.cpp, what assignment statement calculates
the area of the rectangle? Place your answer on the answer sheet.
After the area is calculated, it is displayed using the output statement
cout << "\nArea of rectangle is " << area << endl;The \n at the beginning of the label is a newline character that will result in a blank line before "Area …". The endl manipulator also skips to a new line; it should be used instead of \n at the end of a bunch of output since it ensures that the display will take place immediately. This can make debugging your programs easier.
Using the
vi
editor, create a C++ program, lab4ex3.cpp,
that prompts for and inputs the height and base length
for a pyramid, and displays its volume with an appropriate label.
Compile and run the program to make sure there are
no errors and that it generates correct output.
Use 147 as the height value and 230 as base length.
Create a script log, called lab4ex3.log
of a print, a C++ compile, and a run of these activities by typing
$ script lab4ex3.log $ pr -n -t -e4 lab4ex3.cpp $ c++ lab4ex3.cpp -o lab4ex3 $ lab4ex3 ... enter requested data here ... $ exit
Manipulating string data
The data type string has many useful functions associated with it.
This section examines a few of these functions.
The length function returns the length of a string. For example, if a program includes the statements
string str;then it displaysstr = "C++ is fun";
cout << "The string " << str << " is "
<< str.length() << " characters long" << endl;
The string C++ is fun is 10 characters longwhen executed. The syntax of this function call is a bit unusual. You logically would expect length(str) rather than str.length(). The reason is technical and will be covered in more detail later, but it has to do with the fact that this length function is a member function for the class string. It can be thought of as a message being sent to str: "str, tell me your length!"
The substr function is used to extract a substring from a string. It has two arguments, (1) the starting position of the desired substring and (2) the length of the substring. The position is counted from zero.
Using the string str containing "C++ is fun" you could picture the positions
of the characters in str as
position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
character | C | + | + | i | s | f | u | n |
Here are some examples of values returned by substr:
str.substr(0,3) returns "C++"
str.substr(5,4) returns "s fu"
A length of 0 results in an empty string. If the length argument specifies more characters than are available, then the substr function returns as many characters as it can. However, if the starting position is not in the string, then a run-time error occurs.
The find function is used to find the starting position of one string in another. Again assuming that str contains "C++ is fun" here are examples of values returned by find:
str.find("is") returns 4
str.find("C++") returns 0
str.find("xyz") returns 4294967295.
This value indicates that "xyz" isn't a substring of str. The value
4294967295 is system-specific, but string::npos is its value on any system.
There is also a find function with a character argument. For example,
str.find('+') returns 1
the position of the first +. When all you need is one character, it is usually better to use a character like '+' rather than a single-character string like "+".
courseName.length()
courseName.substr(0, 8)
courseName.substr(7, 10)
courseName.find("Science")
courseName.find("science") [Hint: find is case-sensitive]
courseName.find('t')
The file cla4b.cpp contains a C++ program that will input a person's name (in the format first name followed by a slash followed by last name -- no spaces) into a single string variable. It then finds the slash and uses the position of the slash to put the first name and last name into separate string variables. Finally it calls a function DisplayName to output the name in the format last name followed by comma followed by first name.
slashPosn
lastNameLength
Notice the use of the function DisplayName. This function is declared void since it does not return a value -- it exists to do a job. A void function is called by giving its name and arguments as a stand-alone statement, rather than as part of a larger expression.
$ script lab4ex6.log $ pr -n -t -e4 lab4ex6.cpp $ c++ lab4ex6.cpp -o lab4ex6 $ lab4ex6 ... enter requested data here ... $ exit
Manipulating numeric data
You previously met the data types float and int. Now it is time
to learn additional operators and functions that can be used with these
types.
The data type int has several additional operators defined. The operator / is used for division. This is whole number division like you learned in grade school — when you divide two ints, the fractional part is discarded and you get an int. For example, 13 / 4 has value 3 and -7 / 2 has value -3. If you want the remainder, you can get it with the modulus operator %. For example 13 % 4 has value 1 and -7 % 2 has value -1.
C++ has handy increment and decrement operators that can be used to add 1 to or subtract 1 from an int variable. These are ++ and --, respectively, and can be written either before or after the variable they are changing. For example, if nbr is an int variable that contains 5, then ++nbr; changes the stored value to 6. Similarly if nbr starts at 5, then --nbr; changes the stored value to 4. Increment and decrement operators can be used in bigger expressions, too, but you would be wise to avoid this for now.
The library <cstdlib> contains an absolute value function (and many other things). These are ordinary functions. For example, abs(-45) returns 45.
nbr1 = 35 / 6; nbr2 = 35 % 6; nbr3 = 35; ++nbr3; nbr4 = 21; --nbr4; nbr5 = abs(50);
There is also a division operator / defined for float types. It gives fractional values. For example 7.0 / 2.0 = 3.5.
The library <cmath> contains many useful mathematical functions, including trigonometric and other transcendental functions. Some of the most useful are
sqrt — returns the square root of a float value
fabs — returns the absolute value of a float value
floor — returns the largest whole number less than or equal
to a float value
ceil — returns the smallest whole number greater than or equal
to a float value
pow — returns a float raised to a float power
For example
sqrt (1.44) returns 1.2
fabs(5.7) returns 5.7
floor(5.7) returns 5.0
ceil(5.7) returns 6.0
floor(-5.7) returns -6.0
ceil(-5.7) returns -5.0
pow(2.5, 3.0) returns 15.625
8.0 / 5.0 8 / 5 sqrt(20.25) fabs(-20.25) floor(20.25) ceil(20.25) floor(-1.3) ceil(-7.9) pow(4.5, 2.0)
Formatting output
This section introduces a few methods of making C++ output prettier.
Let's start with a "plain" version of a program and then change it to a
"fancy" version.
Suppose that you take out a loan for D dollars, to be repaid in monthly
payments over Y years and the annual interest rate is R. Then the
amount of each monthly payment P is
The file cla4c.cpp contains a C++ program that will prompt for and input a loan amount, an annual interest rate (like .06 for 6%) and a number of years. It is supposed to calculate the monthly payment, but the correct assignment statement has been replaced by
payment = -99.99;
The library <iomanip> contains a collection of I/O manipulators that can be used to make neat output. These include setw(), fixed, and setprecision().
setw() sets the width of the next output. For example,
cout << '*' << setw(4) << 99 << '*' << endl;will display * 99* with exactly two blanks.
fixed suppresses scientific notation in floating-point output and
setprecision() sets the number of digits to be displayed after
the decimal point.
Then
cout << fixed << setprecision(2) << 6.0 << endl;displays 6.00.
Exercise 10:
Modify your program from exercise 9 so that
the monthly payment is displayed as money
(that is, with exactly two digits after the decimal point).
Create a script log, called lab4ex10.log
of a print, a C++ compile, and a run of these activities by typing
$ script lab4ex10.log $ pr -n -t -e4 cla4c.cpp $ c++ cla4c.cpp -o lab4ex10 $ lab4ex10 ... enter requested data here ... $ exit
Submit the log files you have created in Lab 4 typing
$ handin lab4log lab4ex3.log lab4ex6.log lab4ex10.logFrom the PC you are working on, you must also submit the answer sheet (AnswerSheet4.pdf) using the following directions:
Congratulations!
You have finished Lab 4.
Code for Lab 4 (Do not copy/paste)
// cla4a.cpp // program to calculate the area of a rectangle #include <iostream> using namespace std; int main() { float length; float width; float area; cout << "Enter length of rectangle: "; cin >> length; cout << "Enter width: "; cin >> width; area = length * width; cout << "\nArea of rectangle is " << area << endl; return 0; } // cla4b.cpp // program to change the format of a name #include <iostream> #include <string> using namespace std; // display name using format name2, name1 void DisplayName(string name1, string name2); int main() { string name; string firstName; string lastName; int slashPosn; int lastNameLength; cout << "Enter name (first and last separated by a /): "; cin >> name; slashPosn = name.find('/'); firstName = name.substr(0, slashPosn); lastNameLength = name.length() - slashPosn - 1; lastName = name.substr(slashPosn+1, lastNameLength); cout << "Reversed, the name is "; DisplayName(firstName, lastName); cout << endl; return 0; } // display name using format name2, name1 void DisplayName(string name1, string name2) { cout << name2; cout << ", "; cout << name1; } // cla4c.cpp // program to calculate loan payment amount #include <iostream> #include <cmath> using namespace std; int main() { int nbrYears; float rate; float loanAmount; float payment; cout << "Enter loan amount: "; cin >> loanAmount; cout << "Enter number of years: "; cin >> nbrYears; cout << "Enter interest rate (like .06 for 6%): "; cin >> rate; payment = -99.99; // replace this assignment statement cout << "Monthly payment: " << payment << endl; return 0; }