+ All Categories
Home > Documents > Chapter Two: Fundamental Data Types

Chapter Two: Fundamental Data Types

Date post: 20-Dec-2021
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
119
Chapter Two: Fundamental Data Types
Transcript
Page 1: Chapter Two: Fundamental Data Types

Chapter Two: FundamentalData Types

Page 2: Chapter Two: Fundamental Data Types

Chapter GoalsTo be able to define and initialize variables and constants

To understand the properties and limitations of integer and floating-point numbers

To write arithmetic expressions and assignment statements in C++

To appreciate the importance of comments and good code layout

To create programs that read and process input, and display the results

To process strings, using the standard C++ string type

Page 3: Chapter Two: Fundamental Data Types

Variables

A variable is used to store information:

◦the contents of the variable:◦ can contain one piece of information at a time.

◦ Has an identifier : The name of the variable

The programmer should pick a good name◦ A good name describes the contents of the variable or what the variable will be used for

Page 4: Chapter Two: Fundamental Data Types

Variables

Parking garages store cars.

Page 5: Chapter Two: Fundamental Data Types

Each parking space is identified

– like a variable’s identifier

Variables

A each parking space in a garage “contains” a car– like a variable’s current contents.

Page 6: Chapter Two: Fundamental Data Types

Variablesand

each space can contain only one car

and

only cars, not buses or trucks

Page 7: Chapter Two: Fundamental Data Types

Variable Definitions

When you define a variable, you are creating it for the first time in memory. We can also call this declaring the variable.

The programmer specifies the type of information to be stored.

Unlike a parking space, a variable is often given an initial value.◦ Initialization is putting a value into a variable when the variable is created.

◦ Initialization is not required in all instances.

Page 8: Chapter Two: Fundamental Data Types

Variable DefinitionsFormat to define a variable:

This creates it in memory. You cannot use a variable in any way until it has been defined.

datatype name;

Format to define AND initialize a variable:

This creates it in memory and gives it a starting (initial) value

datatype name = value;

Page 9: Chapter Two: Fundamental Data Types

Variable Definitions - ExampleThe following statement defines a variable.

int cansPerPack = 6;

cansPerPack is the variable’s name.

data type

indicates that the variable cans_per_pack

will be used to hold integers. = 6

indicates that the variable cans_per_pack will initially contain the

value 6.

Page 10: Chapter Two: Fundamental Data Types
Page 11: Chapter Two: Fundamental Data Types

Number TypesWhen assigning a value to a variable, you are writing a number literal

A number written by a programmer is called a number literal.

When writing a number literal:

Do not include any symbols in the number:

$ % , are not allowed as part of the number

only numbers, decimal points and negative signs are allowed

Page 12: Chapter Two: Fundamental Data Types

An int is the most common data type used to store whole numbers.

A double is the most common data type used to store decimal numbers.

NumberTypes Number Type Comment

6 int An integer has no fractional (decimal) part

-6 int Integers can be negative

0 int Zero is an int

.5 doubleA number with a fractional(decimal) part can be defined

as a double

1.0 double A whole number with a decimal part is a double

1E6 doubleA number in exponential notation always has a type

double

100,000 Error: Do not use a comma in a number literal

3 ½Error: do not use any symbols Use decimals and not

fractions

7.5%

Error: Do not use a symbol – must change any

percent to its decimal equivalent. 7.5% is .075

$25.15Error: No symbols are allowed just use the value

Page 13: Chapter Two: Fundamental Data Types

Variable Names

When you define a variable, you should pick a name that explains its purpose.

For example, it is better to use a descriptive name, such as can_volume, than a short name, such as cv.

Page 14: Chapter Two: Fundamental Data Types

Variable Names

In C++, there are a few simple rules for variable names:

1. Variable names must start with a letter or the underscore ( _ ) character, and the remaining characters must be letters numbers, or underscores.

Page 15: Chapter Two: Fundamental Data Types

2. You cannot use other symbols such as $ or %. Spaces

are not permitted inside names; you can use an underscore instead, as in can_volume or camel case as

in canVolume.

2.Variable names are case-sensitive, that is, can_volume

and can_Volume are different names.

For that reason, it is a good idea to use only lowercase

letters in variable names. (except in camel case)

3.You cannot use reserved words such as double or

return as names; these words are reserved exclusively

for their special C++ meanings.

Page 16: Chapter Two: Fundamental Data Types
Page 17: Chapter Two: Fundamental Data Types

Changing a Variable's ValueThe contents in variables can “vary” over time (hence the name!).

Variables can be changed by

◦assigning to them◦ The assignment statement

◦using the increment or decrement operator

◦ inputting a value into them◦ The input statement

Page 18: Chapter Two: Fundamental Data Types

The Assignment OperatorAn assignment operator is used to store a new value in a variable, replacing the previously stored value.

cans_per_pack = 8;

This assignment statement changes the value stored in cans_per_pack to be 8.

The previous value is replaced with the new value.

Page 19: Chapter Two: Fundamental Data Types

The Assignment Statement

Page 20: Chapter Two: Fundamental Data Types

The Assignment Statement

There is an important difference between a variable definition and an assignment statement:

int cans_per_pack = 6; // Variable definition

...

cans_per_pack = 8; // Assignment statement

The first statement is the definition of cans_per_pack.

The second statement is an assignment statement.An existing variable’s contents are replaced.

Page 21: Chapter Two: Fundamental Data Types

The Assignment StatementThe = in an assignment does not mean the left handside is equal to the right hand side as it does in math.

= is an instruction to do something:copy the value of the expression on the rightinto the variable on the left. It only works in this direction

variable = value; the value can be a number literal or another variable.

Consider what it would mean, mathematically, to state:counter = counter + 2;

counter EQUALS counter + 2 ?

Page 22: Chapter Two: Fundamental Data Types

The Assignment Statement

counter = 11; // assign the value of 11 to counter – previous value is replaced

counter = counter + 2; // add 2 to counter and assign it back to counter

1. Look up the current value of counter (11)

2. Add 2 to that value (13)

3. Assign the result of the addition expression into the variable on the left, changing it.

cout << counter << endl; 13 is the output

Page 23: Chapter Two: Fundamental Data Types

ConstantsSometimes the programmer knows certain values just from analyzing the problem, for this kind of information, programmers use the reserved word const.

The reserved word const is used to define a constant.

A const is a variable whose contents cannot be changed and must be set when created.(Most programmers just call them constants, not variables.)

Constants are commonly written using capital letters to distinguish them visually from regular variables:

const double BOTTLE_VOLUME = 2;

Page 24: Chapter Two: Fundamental Data Types

Constants

Because they cannot change in the run of the program, constants must be initialized when they are defined (declared).

Page 25: Chapter Two: Fundamental Data Types

ConstantsAnother good reason for using constants is to give clarity to calculations:

double volume = bottles * 2;

What does that 2 mean?

Page 26: Chapter Two: Fundamental Data Types

Constants

If we use a constant there is no question:

double volume = bottles * BOTTLE_VOLUME;

Page 27: Chapter Two: Fundamental Data Types

ConstantsAnd still another good reason for using constants:

double bottle_volume = bottles * 2;

double can_volume = cans * 2;

What does that 2 mean?

it is called a “magic number” because it would require magic to know what 2 means.

It is not good programming practice to use magic numbers.

Use constants instead

Page 28: Chapter Two: Fundamental Data Types

ConstantsAnd it can get even worse …

Suppose that the number 2 appears hundreds of times throughout a five-hundred-line program?

Now we need to change the BOTTLE_VOLUME to 2.23 (because we are now using a bottle with a different shape)

How to change only some of those magic numbers 2’s?

Page 29: Chapter Two: Fundamental Data Types

ConstantsConstants to the rescue!

const double BOTTLE_VOLUME = 2.23;

const double CAN_VOLUME = 2;

double bottle_vol = bottles * BOTTLE_VOLUME;

double can_vol = cans * CAN_VOLUME;

(Look, no magic numbers!)

Page 30: Chapter Two: Fundamental Data Types

AssignmentDeclare two constants named ONE & TWO.

Initialize ONE to 1 and TWO to 2.2

Declare a variable of the type int named three and an int named four.

Initialize three to the value of the variable ONE

Initialize four to to the value of the variable TWO.

Write statements to print three and four to the screen.

After the output statements, change the value of ONE to 5 and TWO to 3.5. (notice what happens when you compile)

Now change the value of three to 10 and four to 15.65.

Output three and four again.

Page 31: Chapter Two: Fundamental Data Types

CommentsRemember that comments are explanations for human readers of your code (other programmers).

The compiler ignores comments completely.

double can_volume = 0.355; // Liters in a 12-ounce can

Comment

C++ for Everyone by Cay Horstmann

Copyright © 2012 by John Wiley & Sons. All rights reserved

Page 32: Chapter Two: Fundamental Data Types

CommentsComments can be written in two styles:

Single line:

double can_volume = 0.355; // Liters in a 12-ounce can

The compiler ignores everything after // to the end of line

Multiline for longer comments:

/*This program computes the volume (in liters)of a six-pack of soda cans.

*/

Page 33: Chapter Two: Fundamental Data Types

Common Error – Using Undefined Variables

You must define a variable before you use it for the first time.

For example, the following sequence of statements would not be legal:

double can_volume = 12 * liter_per_ounce;

double liter_per_ounce = 0.0296;

Statements are compiled in top to bottom order.

When the compiler reaches the first statement, it does not know that liter_per_ounce will be defined in the next line, and it reports an error.

?

Page 34: Chapter Two: Fundamental Data Types

Common Error – Using Uninitialized Variables

Initializing a variable is not required, but there is always a value in every variable, even uninitialized ones.Some value will be there, the flotsam left over from some previous calculation or simply the random value there when the transistors in RAM were first turned on.

int bottles; // Forgot to initialize

int bottle_volume = bottles * 2;

What value would be output from the following statement?

cout << bottle_volume << endl;// Unpredictable

// Result is unpredictable

Page 35: Chapter Two: Fundamental Data Types

Numeric Types in C++

In addition to the int and double types, C++ has other numeric types.

C++ has two other floating-point types.

1. float

The float type uses half the storage of the double type that we use in this book, but it can only store 6–7 digits.

Page 36: Chapter Two: Fundamental Data Types

Numeric Types in C++Many years ago, when computers had far less memory than they have today, floatwas the standard type for floating-point computations, and programmers would indulge in the luxury of “double precision” only when they really needed the additional digits.

Today, the float type is rarely used.

2. long double - for quadruple precision.Most contemporary compilers use this type when a programmer asks for a doubleso just choosing double is what is done most often.

Page 37: Chapter Two: Fundamental Data Types

Numeric Types in C++In addition to the int type, you can also use these integer types:

• short

• long

For each integer type, there is an unsigned equivalent for when data will never be negative

unsigned short, unsigned long

For example, the short type typically has a range from –32,768 to 32,767, whereas unsigned short has a range from 0 to 65,535. These strange-looking limits are the result of the use of binary numbers in computers.

A short value uses 16 binary digits, which can encode 216 = 65,536 values.

Page 38: Chapter Two: Fundamental Data Types

Numeric Types in C++

Page 39: Chapter Two: Fundamental Data Types

Numeric Ranges and PrecisionsThe int type has a limited range:

On most platforms, it can represent numbers up to a little more than two billion.

For many applications, this is not a problem, but you cannot use an int to represent the world population.

If a computation yields a value that is outside the int range, the result overflows.

No error is displayed. Instead, the result is truncated to fit into an int, yielding a value that is most likely not what you thought.

Page 40: Chapter Two: Fundamental Data Types

Numeric Ranges and PrecisionsFor example:

int one_billion = 1000000000;

cout << 3 * one_billion << endl;

displays –1294967296 because the result is larger than an int can hold.

In situations such as this, you could instead use the double type.

However, you will need to think about a related issue: roundofferrors.

Page 41: Chapter Two: Fundamental Data Types

Arithmetic OperatorsC++ has the same arithmetic

operators as a calculator:

* for multiplication: a * b

(not a . b or ab as in math)

/ for division: a / b

(not ÷ or a fraction bar as in math)

+ for addition: a + b

- for subtraction: a – b

Page 42: Chapter Two: Fundamental Data Types

Arithmetic Operators

Just as in regular algebraic notation,* and / have higher precedencethan + and –.

In a + b / 2,the b / 2 happens first.

Page 43: Chapter Two: Fundamental Data Types

Increment and DecrementChanging a variable by adding or subtracting 1 is so common that there is a special shorthand for these:

The increment and decrement operators.

counter++; // add 1 to counter

counter--; // subtract 1 from counter

Page 44: Chapter Two: Fundamental Data Types

Increment and Decrement

C++ was based on C and so it’s one better than C, right?

Guess how C++ got its name!

Page 45: Chapter Two: Fundamental Data Types

Compound Operators – using assignment

The statement number = number + 5; is an example of an accumulation statement. The old value of number is incremented by 5 and the new value is stored back in number.

The above statement can be replaced as follows: number += 5;

C++ provides the following assignment operators:

+= -= *= /= %=

Page 46: Chapter Two: Fundamental Data Types

Examples using the compound operator

Using the Compound Operator Writing it the long way

rate *= 1.05; rate = rate * 1.05;

sum += 25; sum = sum + 25;

number %= 5; number = number % 5;

Page 47: Chapter Two: Fundamental Data Types

Integer DivisionWhen you divide two integers, you only get an integer as an answer. You will never get a decimal answer when dividing 2 int’s. Even if you try to store it in a double, the decimal portion is lost; cut-off.

int cost = 6;

int sales= 10;

int profitAmt = sales-cost;

double profitPct = profitAmt/sales;

profitPct will have the value of 0 and not .4 as it should have. Even though you stored it in a double, the decimal value of the division is lost before it is stored into memory.

Page 48: Chapter Two: Fundamental Data Types

Integer Division and Remainder

The % operator computes the remainder of aninteger division.

It is called the modulus operator(also modulo and mod)

It has nothing to do with the % key on a calculator

Page 49: Chapter Two: Fundamental Data Types

Integer Division and RemainderTime to break open the piggy bank.

You want to determine the value in dollars and cents

stored in the piggy bank.

You obtain the dollars through an integer division by

100.

The integer division discards the remainder.

To obtain the remainder, use the % operator:

int pennies = 1729;

int dollars = pennies / 100; // Sets dollars to 17

int cents = pennies % 100; // Sets cents to 29

Page 50: Chapter Two: Fundamental Data Types

The modulus operator can only be

used with integers

Page 51: Chapter Two: Fundamental Data Types

Converting Floating-Point Numbers to IntegersWhen a floating-point value is assigned to an integer variable, the fractional part is discarded:

double price = 2.55;

int dollars = price; // Sets dollars to 2

You probably want to round to the nearest integer.To round a positive floating-point value to the nearest integer, add 0.5 and then convert to an integer:

int dollars = price + 0.5; // Rounds to the nearest integer

Page 52: Chapter Two: Fundamental Data Types

What about this?

Inside the parentheses is easy: 1 + (r / 100)

But that raised to the n?

Powers and Roots

1001

rn

b

Page 53: Chapter Two: Fundamental Data Types

Powers and RootsIn C++, there are no symbols for powers and roots.To compute them, you must call functions.

The C++ library defines many mathematical functions such as sqrt(square root) and pow (raising to a power).

To use the functions in this library, called the cmath library, you must add a compiler directive:

#include <cmath>

at the top of your program file.

Page 54: Chapter Two: Fundamental Data Types

Powers and RootsThe power function has the base followed by a comma

followed by the power to raise the base to:

pow(base, exponent)

Using the pow function:

b * pow(1 + r / 100, n)

Page 55: Chapter Two: Fundamental Data Types

Powers and Roots

Page 56: Chapter Two: Fundamental Data Types

Other Mathematical Functions

Page 57: Chapter Two: Fundamental Data Types

Common Error – Unintended Integer Division

If both arguments of division are integers, the remainder is discarded:7 / 3 is 2, not 2.5

but7.0 / 4.0

7 / 4.0

7.0 / 4

all yield 1.75.

Page 58: Chapter Two: Fundamental Data Types

Common Error – Unintended Integer Division

It is unfortunate that C++ uses the same symbol: / for both integer and floating-point division.These are really quite different operations.

It is a common error to use integer division by accident.Consider this segment that computes the average of three integers:

int s1,s2,s3;

cout << "Please enter your last three test scores: ";

cin >> s1 >> s2 >> s3;

double average = (s1 + s2 + s3) / 3;

cout << "Your average score is " << average << endl;

Page 59: Chapter Two: Fundamental Data Types

Common Error – Unintended Integer DivisionWhat could be wrong with that?

Of course, the average of s1, s2, and s3 is

(s1+ s2+ s3) / 3

Here, however, the / does not mean division in the mathematical sense.

It denotes integer division because

both (s1 + s2 + s3)and 3 are integers.

Page 60: Chapter Two: Fundamental Data Types

Common Error – Unintended Integer Division

For example, if the scores add up to 14, the average is computed to be 4.

WHAT?

Yes, the result of the integer division of 14 by 3 is 4.

How many times does 3 evenly divide into 14?

That integer 4 is then moved into the floating-point variable average.

So 4.0 is stored. That’s not what I want!

Page 61: Chapter Two: Fundamental Data Types

Common Error – Unintended Integer Division

The remedy is to make the numerator or denominator into a floating-point number:

double total = s1 + s2 + s3;

double average = total / 3;

or

double average = (s1 + s2 + s3) / 3.0;

Page 62: Chapter Two: Fundamental Data Types

Input

Sometimes the programmer does not know what shouldbe stored in a variable – but the user does.

The programmer must get the input value from the user

◦ Users need to be prompted(how else would they know they need to type something?

◦ Prompts are done in output statements

The keyboard needs to be read from

◦ This is done with an input statement

Page 63: Chapter Two: Fundamental Data Types

Input

The input statement

◦ To read values from the keyboard, you input them from an object called cin.

◦ The >> is the extraction operator.

◦ This operator is then followed by the variable where the extracted data is stored.

cin >> bottles; is an input statement.

Of course, bottles must be defined earlier.

Page 64: Chapter Two: Fundamental Data Types

InputYou can read more than one value in a single input statement:

cout << "Enter the number of bottles and cans: ";

cin >> bottles >> cans;

The user can supply both inputs on the same line:

Enter the number of bottles and cans: 2 6

Page 65: Chapter Two: Fundamental Data Types

InputAlternatively, the user can press the Enter key after each input:

cout << "Enter the number of bottles and cans: ";

cin >> bottles >> cans;

Screen looks like:

Enter the number of bottles and cans: 2

6

Page 66: Chapter Two: Fundamental Data Types

Input Statement

Page 67: Chapter Two: Fundamental Data Types

Formatted OutputWhen you print an amount in dollars and cents,you usually want it to be rounded to two significant digits.

You learned how to actually round off and store a value but, for output, we want to round off only for display.

A manipulator is something that is sent to cout to specify how values should be formatted.

To use manipulators, you must include the iomanipheader in your program:

#include <iomanip>

Page 68: Chapter Two: Fundamental Data Types

Formatted Output

Which do you think the user prefers to see?

Price per liter: $1.22

or

Price per liter: $1.21997

Page 69: Chapter Two: Fundamental Data Types

setprecision()

setprecision() is a manipulator used to set the number of decimal precision of floating point numbers.

Page 70: Chapter Two: Fundamental Data Types

setprecision()

Use with fixed to set the precision after the decimal point.

This sets the output from this point forward. You do not need to do this more than once unless you are changing the precision like shown above.

Page 71: Chapter Two: Fundamental Data Types

Set it once and all floating point values will print with that precision

Page 72: Chapter Two: Fundamental Data Types

Formatted Output

Page 73: Chapter Two: Fundamental Data Types

Formatted Output

You can combine manipulators and values to be displayed into a single statement:

price_per_liter = 1.21997;

cout << fixed << setprecision(2)

<< "Price per liter: $"

<< price_per_liter << endl;

This code produces this output:

Price per liter: $1.22

Page 74: Chapter Two: Fundamental Data Types

setw()

Use the setw manipulator 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.

Page 75: Chapter Two: Fundamental Data Types

Formatted Output

If you want columns of certain widths, use the setw manipulator.

By default, the setw() will right align the value in the field width you specify.

For example, if you want a number to be printed, right justified, in a column that is eight characters wide, you use

cout << setw(8) << number;

Page 76: Chapter Two: Fundamental Data Types

Without a field width set: With a field width set to 8:

You can see the default, right alignment on the number. The output is padded with spaces in front of the output

Page 77: Chapter Two: Fundamental Data Types

Adjust output to the Left side of the fieldWhen the output field is set to left, the output is padded to the field width by inserting fill characters at the end, effectively adjusting the field to the left.

Page 78: Chapter Two: Fundamental Data Types

Formatted OutputThere is a notable difference between the

setprecision and setw manipulators.

Once you set the precision, it is used for all floating-point numbers until the next time you set the precision.

But setw affects only the next value.

Subsequent values are formatted without added spaces.

Page 79: Chapter Two: Fundamental Data Types

This code:

double price_per_ounce_1 = 10.2372;

double price_per_ounce_2 = 117.2;

double price_per_ounce_3 = 6.9923435;

cout << fixed << setprecision(2); Set the output to 2 decimals

cout << setw(8) << price_per_ounce_1<<endl;

cout << setw(8) << price_per_ounce_2<<endl;

cout << setw(8) << price_per_ounce_3<<endl;

cout << "--------" << endl;

Produces this output:

10.24

117.20

6.99

--------

Page 80: Chapter Two: Fundamental Data Types

We often use the default right alignment when printing values with a decimal point underneath one another so the decimal will line up.

Using the left option here would not give the best output:

Page 81: Chapter Two: Fundamental Data Types

Clearing the Screen Sometimes it is helpful to clear the screen before displaying the final output.

When the screen is cleared in C++, the cursor is moved to the upper left corner of the screen.

To clear the screen in C++, utilize the code: system("CLS"); or system("cls");

You will need to include the standard library header file

#include <stdlib.h>

Page 82: Chapter Two: Fundamental Data Types

StringsStrings are sequences of characters:

"Hello World"

If you include the string header, you can create variables to hold literal strings:

#include <string> // optional for most compilers

using namespace std;

int main()

{

string name = "Harry"; // literal string "Harry" stored

string name("Harry");

Page 83: Chapter Two: Fundamental Data Types

StringsString variables are guaranteed to be initialized even if you don’t initialize them:

string response; // literal string "" stored

"" is called the empty or null string.

Page 84: Chapter Two: Fundamental Data Types

Other Ways to Construct a stringstring ( other_string, position, count )

Creates a string that contains count characters from other_string, starting at position.

If count is missing (only the first two arguments are given), all the characters from other_string, starting at position and going to the end of other_string, are included in the new string.

string ( count, character )

Create a string containing character repeated count times

Page 85: Chapter Two: Fundamental Data Types

Examples:

string s1; // s1 = ""

string s2( "abcdef" ); // s2 = "abcdef"

string s3( s2 ); // s3 = "abcdef"

string s4( s2, 1 ); // s4 = "bcdef"

string s5( s2, 3, 2 ); // s5 = "de"

string s6( 10, '-' ); // s6 = "----------"

Page 86: Chapter Two: Fundamental Data Types

Concatenation OperatorUse the + operator to concatenate strings; that is, put them together to yield a longer string.

string fname = "Harry";

string lname = "Morgan";

string name = fname + lname;

cout << name << endl;

name = fname + " " + lname;

cout << name << endl;

The output will be HarryMorgan

Harry Morgan

Page 87: Chapter Two: Fundamental Data Types

Common Error – Concatenation of literal strings

Literal strings cannot be concatenated.

// will not compile

string greeting = "Hello, " + " World!";

You can concatenate a literal string with a variable but not two separate literal strings.

Page 88: Chapter Two: Fundamental Data Types

String InputYou can read a string from the console:

string name;

cout << "Please enter your name: ";

cin >> name;

When a string is read with the >> operator, only one word is placed into the string variable.

For example, suppose the user types

Harry Morgan

as the response to the prompt.This input consists of two words. Only the string "Harry" is placed into the variable name.

Page 89: Chapter Two: Fundamental Data Types

String InputYou can use another input to read the second word.

cout << "Please enter your name: ";

string fname, lname;

cin >> fname >> lname;

BETTER YET, use getline()

The getline method is used to input an entire line entered by the user.

Example: cout << "Enter your first name: ";

getline(cin, FirstName);

gets Harry

gets Morgan

Page 90: Chapter Two: Fundamental Data Types

String Functions

The length member function yields the number of characters in a string.

Unlike the sqrt or pow function, the length function is invoked with the dot notation:

int n = name.length();

n will then contain the length of the name string

Only a string object can call a string function

Page 91: Chapter Two: Fundamental Data Types

String Functions: substr(start, length)Once you have a string, you can extract substrings by using the substrmember function.

s.substr(start, length)

returns a string that is made from the characters in the string s, starting at character start, and containing length characters. (start and length are integer values).

string greeting = "Hello, World!";

string sub = greeting.substr(0, 5);

// sub contains "Hello"

Page 92: Chapter Two: Fundamental Data Types

String Functions

0 ?

string sub = greeting.substr(0, 5);

Page 93: Chapter Two: Fundamental Data Types

String Functions

string greeting = "Hello, World!";

string w = greeting.substr(7, 5);

// w contains "World" (not the !)

"World" is 5 characters long but…

why is 7 the position of the “W” in "World"?

Page 94: Chapter Two: Fundamental Data Types

String Functions

H e l l o , W o r l d !

0 1 2 3 4 5 6 7 8 9 10 11 12

In most computer languages, the starting position 0 means

“start at the beginning.”

The first position in a string is labeled 0, the second one 1, and so

on. And don’t forget to count the space character after the comma—

but the quotation marks are not stored.

Page 95: Chapter Two: Fundamental Data Types

String FunctionsH e l l o , W o r l d !

0 1 2 3 4 5 6 7 8 9 10 11 12

The position number of the last character is always one less than the length of the string

The ! is at position 12 in "Hello, World!". The length of "Hello, World!" is 13.

(C++ remembers to count the 0 as one of the positions when counting characters in strings.)

Page 96: Chapter Two: Fundamental Data Types

String Functions: substr(start)

H e l l o , W o r l d !

0 1 2 3 4 5 6 7 8 9 10 11 12

string greeting = "Hello, World!";

string w = greeting.substr(7); // 7 represents the starting value

// w contains "World!"

If you do not specify how many characters to take, you get all the rest.

Page 97: Chapter Two: Fundamental Data Types

String Functions

H e l l o , W o r l d !

0 1 2 3 4 5 6 7 8 9 10 11 12

string greeting = "Hello, World!";

string w = greeting.substr();

// w contains "Hello World!"

If you omit the starting position and the length, you get all the characters

(not much of substring!)

Page 98: Chapter Two: Fundamental Data Types

String Operations

Page 99: Chapter Two: Fundamental Data Types

String Operations

Page 100: Chapter Two: Fundamental Data Types

Casts

Occasionally, you need to store a valueinto a variable of a different type.

Whenever there is the risk of information loss,the compiler generally issues a warning.

It’s not a compilation error to lose information.

But it may not be what a programmer intended.

Page 101: Chapter Two: Fundamental Data Types

CastsFor example, if you store a double value into an int variable, information is lost in two ways:

The fractional part will be lost.

int n = 1.99999; // NO

1 is stored (the decimal part is truncated)

The magnitude may be too large.

int n = 1.0E100; // NO

is not likely to work, because 10100 is larger than the largest representable integer.

Page 102: Chapter Two: Fundamental Data Types

Casts

A cast is a conversion from one type

(such as double)

to another type (such as int).

This is not safe in general, but if you know it to be

safe in a particular circumstance, casting is the only

way to do the conversion.

Page 103: Chapter Two: Fundamental Data Types

Casts

Nevertheless, sometimes you do want to convert

a floating-point value into an integer value.

If you are prepared to lose the fractional part and you

know that this particular floating point number is not

larger than the largest possible integer, then you can

turn off the warning by using a cast.

Page 104: Chapter Two: Fundamental Data Types

Casts

It’s not really about turning off warnings…

Sometimes you need to cast a value to a different type.

Consider money.

(A good choice of topic)

(and remember Penny?)

and still in

one piece

Page 105: Chapter Two: Fundamental Data Types

Castsdouble change; // change owed

change = 999.89;

To annoy customers who actually want change when they pay with $10000 bills, we say:

“Sorry, we can only give change in pennies.”

How many pennies do we owe them?

We need to cast the change owed

into the correct type for pennies.

Page 106: Chapter Two: Fundamental Data Types

Casts

A bank would round down to the nearest penny, of course, but we will do the right thing

How to "round up" to the next whole penny?

Add 0.5 to the change and then cast that amount into an int value, storing the number of pennies into an int variable.

int cents; // pennies owed

C++ for Everyone by Cay Horstmann

Copyright © 2012 by John Wiley & Sons. All rights reserved

Page 107: Chapter Two: Fundamental Data Types

Casts

You express a cast in C++ using a static_cast

static_cast< >( )

C++ for Everyone by Cay Horstmann

Copyright © 2012 by John Wiley & Sons. All rights reserved

Page 108: Chapter Two: Fundamental Data Types

Casts

change = 999.89; // change owed

int cents = static_cast< >( );

C++ for Everyone by Cay Horstmann

Copyright © 2012 by John Wiley & Sons. All rights reserved

Page 109: Chapter Two: Fundamental Data Types

Castschange = 999.89; // change owed

int cents = static_cast< >( );

You put the type you want to convert to inside the < >

C++ for Everyone by Cay Horstmann

Copyright © 2012 by John Wiley & Sons. All rights reserved

Page 110: Chapter Two: Fundamental Data Types

Castschange = 999.89; // change owed

int cents = static_cast<int>( );

You put the type you want to convert to inside the < >

C++ for Everyone by Cay Horstmann

Copyright © 2012 by John Wiley & Sons. All rights reserved

Page 111: Chapter Two: Fundamental Data Types

Casts

change = 999.89; // change owed

int cents = static_cast<int>( );

You put the type you want to convert to inside the < >

You put the value you want to convert inside the( )

Page 112: Chapter Two: Fundamental Data Types

Castschange = 999.89; // change owed

int cents = static_cast<int>(100 * change + 0.5);

You put the type you want to convert to inside the < >

You put the value you want converted inside the( )

Page 113: Chapter Two: Fundamental Data Types

Castschange = 999.89; // change owed

int cents = static_cast<int>(100 * change + 0.5);

You put the type you want to convert to inside the < >

You put the value you want to convert inside the( )

and you get the value converted to the type: 1000 pennies

Page 114: Chapter Two: Fundamental Data Types

Castschange = 999.89; // change owed

int cents = static_cast<int>(100 * change + 0.5);

You put the type you want to convert to inside the < >

You put the value you want to convert inside the( )

and you get the value converted to the type

1000 will be stored into cents.

Page 115: Chapter Two: Fundamental Data Types

Chapter SummaryWrite variable definitions in C++.

• A variable is a storage location witha name.

• When defining a variable, you usuallyspecify an initial value.

• When defining a variable, you also specify thetype of its values.

• Use the int type for numbers that cannot have afractional part.

• Use the double type for floating-point numbers.

Page 116: Chapter Two: Fundamental Data Types

Chapter Summary

• An assignment statement stores anew value in a variable, replacing thepreviously stored value.

• The assignment operator = doesnot denote mathematical equality.

• You cannot change the value of avariable that is defined as const.

• Use comments to add explanations for humans whoread your code.The compiler ignores comments.

Page 117: Chapter Two: Fundamental Data Types

Chapter SummaryUse the arithmetic operations in C ++.

• Use * for multiplication and / for division.

• The ++ operator adds 1 to a variable;the -- operator subtracts 1.

• If both arguments of / are integers,the remainder is discarded.

• The % operator computes the remainder of aninteger division.

• Assigning a floating-point variable to an integer dropsthe fractional part.

• The C++ library defines many mathematical functions suchas sqrt (square root) and pow (raising to a power).

Page 118: Chapter Two: Fundamental Data Types

Chapter SummaryWrite programs that read user input and write formatted output.

• Use the >> operator to read a value and place it in a variable.

• You use manipulators to specify how values should beformatted.

Carry out hand calculations when developing an algorithm.

• Pick concrete values for a typical situation to use in a handcalculation.

Page 119: Chapter Two: Fundamental Data Types

Chapter SummaryWrite programs that process strings.

• Strings are sequences of characters

• Use the + operator to concatenate strings; that is, put them together to yield a longer string.

• The length member function yields the number of characters in a string.

• A member function is invoked using the dot notation.

• Use the substr member function to extract a substring of a string.


Recommended