Lab 4 Strings & Formatted Output: 4.1 Objectives
Lab 4 Strings & Formatted Output: 4.1 Objectives
The following are some arithmetic operators used to perform different operations on
variables/constants. Most of them are easy to understand and use.
When we divide two integers, of course the result of this division will be an integer. This is because the
decimal part is truncated or “chopped” from the number. Thus 9/5 will give the answer 1 not 1.8. For
this reason there are two division operations for integer numbers. The modulus operator, (%) used only
with integers, gives the remainder of a division operation.
Therefore, 9 / 5 gives 1 while 9 % 5 gives 4 (the remainder of the division).
Activity:
Observe the output of following:
Expressions are evaluated (i.e. simplified and converted to one value) and the result is placed in the
memory location corresponding to the variable on the left. Let’s consider the last expression. Can you
tell in which order it would be evaluated?
The answer depends on the precedence of the operators used in this expression.
Parenthesis
High to low
CONCATENATION
The “+” operator is used to concatenate two strings. For example,
string fname = "Harry";
string lname = "Morgan";
string name = fname + lname;
results in the string
"HarryMorgan"
What if you’d like the first and last name separated by a space? No problem:
string name = fname + " " + lname;
Now the result is
"Harry Morgan"
STRING INPUT
Operation Description
name.length() Computes the length of string
Activity:
Store “Hello world!” in a string variable and perform the above mentioned operations on it.
When you print the result of a computation, you often want some control over its appearance. For
example, when you print an amount in dollars and cents, you usually want it to be rounded to two
significant digits. That is, you want the output to look like
Price per ounce: 0.04
instead of
Price per ounce: 0.0409722
The following command instructs cout to use two digits after the decimal point for all floating-point
numbers:
cout << fixed << setprecision(2);
This command does not produce any output; it just manipulates cout so that it will change the output
format. The values fixed and setprecision are called manipulators.
setw is another manipulator used to set the width of the next output field. The width is the total
number of characters used for showing the value, including digits, the decimal point, and spaces.
Controlling the width is important when you want columns of numbers to line up. For example, if you
want a number to be printed in a column that is eight characters wide, you use
cout << setw(8) << price_per_ounce;
This command prints the value price_per_ounce in a field of width 8, for example
Note: To use manipulators, you must include the <iomanip> header in your program:
#include <iomanip>