ENG2139 Lecture 4
ENG2139 Lecture 4
Time Allocation
• Lectures 2 hours/week
• Laboratory/ Tutorials 3 hours/week
5
Character Function Table
isalpha Returns true (a nonzero number) if the
argument is a letter of the alphabet.
Returns 0 if the argument is not a letter.
int main()
{
char input;
7
Character Case Conversion
• The C++ library provides two functions, toupper and
tolower , for converting the case of a character
• Each of the functions accepts a single character
argument. If the argument is a lowercase letter, the
toupper function returns its uppercase equivalent.
• If the argument is already an uppercase letter,
toupper returns it unchanged
• For example, the following statement will display
the character A on the screen:
cout << toupper('a');
8
• Any nonletter argument passed to toupper is
returned as it is
• toupper and tolower don’t actually cause the
character argument to change, they simply
return the upper- or lowercase equivalent of
the argument
9
C-Strings
• In C++, a C-string is a sequence of characters stored
in consecutive memory locations, terminated by a
null character
• String is a generic term that describes any
consecutive sequence of characters. A word, a
sentence, a person’s name, and the title of a song
are all strings.
• In the C++ language, there are two primary ways
that strings are stored in memory: as string objects,
or as C-strings.
10
• In this section, we will use C-strings, which are
an alternative method for storing and working
with strings.
• In C++, all string literals are stored in memory
as C-strings. Recall that a string literal (or
string constant) is the literal representation of
a string in a program. In C++, string literals are
enclosed in double quotation marks.
11
• The purpose of the null terminator is to mark the end of the C-string.
Without it, there would be no way for a program to know the length of a
C-string
// This program contains string literals.
#include <iostream>
using namespace std;
int main()
{
char again;
do
{
cout << "C++ programming is great fun!" << endl;
cout << "Do you want to see the message again? ";
cin >> again;
} while (again == 'Y' || again == 'y');
return 0;
}
12
• In the C language, all strings are treated as C-
strings.
• When a C programmer wants to store a string
in memory, he or she has to create a char
array that is large enough to hold the string,
plus one extra element for the null character.
13
Library Functions for Working with C-Strings
14
• When using a C-string handling function, you
must pass one or more C-strings as
arguments.
• This means passing the address of the C-
string, which may be accomplished by using
any of the following as arguments:
1. The name of the array holding the C-string
2. A pointer variable that holds the address of
the C-string
3. A literal string
15
• The strcat function accepts two pointers to C-strings
as its arguments. The function concatenates ,or
appends one string to another
strcat(string1, string2);
• The strcat function copies the contents of string2 to
the end of string1
• The strcat function doesn’t insert a space, so it’s the
programmer’s responsibility to make sure one is
already there, if needed.
• It’s also the programmer’s responsibility to make
sure the array holding string1 is large enough to
hold string1 plus string2 plus a null terminator
16
• Recall that one array cannot be assigned to
another with the = operator.
• Each individual element must be assigned,
usually inside a loop.
• The strcpy function can be used to copy one
string to another. If anything is already stored in
the location referenced by the first argument, it is
overwritten.
• Here is an example of its use:
const int SIZE = 13;
char name[SIZE];
strcpy(name, "Albert Einstein");
17
• Because the strcat and strcpy functions can
potentially overwrite the bounds of an array, they
make it possible to write unsafe code.
• As an alternative, you should use strncat and
strncpy whenever possible. The strncat functions
works like strcat , except it takes a third argument
specifying the maximum number of characters
from the second string to append to the first.
• Here is an example call to strncat:
18
• The strstr function searches for a string inside
of a string. For instance, it could be used to
search for the string “seven” inside the larger
string “Four score and seven years ago.”
• The function’s first argument is the string to
be searched, and the second argument is the
string to look for.
• If the function finds the second string inside
the first, it returns the address of the
occurrence of the second string within the
first string
19
• Because C-strings are stored in char arrays, you cannot use the
relational operators to compare two C-strings.
• To compare C-strings, you should use the library function strcmp .
This function takes two C-strings as arguments and returns an
integer that indicates how the two strings compare to each other
21
Function Description
22
• C++ 11 introduces a function named to_string
that converts a numeric value to a string
object.
• Note that the to_string function requires the
string header file to be included.
• Each version of the function accepts an
argument of a numeric data type and returns
the value of that argument converted to a
string object. Here is an example:
int number = 99;
string output = to_string(number);
23
Using the string Class
• Standard C++ provides a special data type for storing and
working with strings.
• The first step in using the string class is to #include the string
header file
• If you want to read a line of input (with spaces) into a string
object, use the getline()
• function. Here is an example:
string name;
cout << "What is your name? ";
getline(cin, name);
• The second argument is the name of a string object. This is
where getline() stores the input that it reads
24
Comparing and Sorting string Objects
• There is no need to use a function such as strcmp to compare
string objects. You may use the < , > , <= , >= , == , and != relational
operators. For example, assume the following definitions exist in a
program:
string set1 = "ABC";
string set2 = "XYZ";
if (set1 < set2)
cout << "set1 is less than set2.\n";
• Relational operators perform comparisons on string objects in a
fashion similar to the way the strcmp function compares C-strings.
• One by one, each character in the first operand is compared with
the character in the corresponding position in the second operand.
If all the characters in both strings match, the two strings are equal.
25
Supported Description
Operator
26
Using string Class Member Functions
• The string class also has member functions. For
example, the length member function returns the
length of the string stored in the object.
• The value is returned as an unsigned integer.
Assume the following string object definition exists
in a program:
string town = "Charleston";
• The following statement in the same program
would assign the value 10 to the variable x .
x = town.length();
27
Type Conversion
• When an operator’s operands are of different data types, C++
will automatically convert them to the same data type. This can
affect the results of mathematical expressions.
• C++ follows a set of rules when performing mathematical
operations on variables of different data types.
• It’s helpful to understand these rules to prevent subtle errors
from creeping into your programs.
• Just like officers in the military, data types are ranked. One data
type outranks another if it can hold a larger number. For
example, a float outranks an int.
• long double>double>float>unsigned long>long>unsigned
int>int
28
• Let’s look at the specific rules that govern the
evaluation of mathematical expressions:
1. char s, short s, and unsigned short s are
automatically promoted to int anytime they are
used in a mathematical expression .
2. When an operator works with two values of
different data types, the lower-ranking value is
promoted to the type of the higher-ranking
value.
3. When the final value of an expression is
assigned to a variable, it will be converted to the
data type of that variable
29
Type Casting
• A type cast expression lets you manually promote or demote a
value. The general format of a type cast expression is:
static_cast< DataType >( Value )
• where Value is a variable or literal value that you wish to
convert and DataType is the data type you wish to convert
Value to. Here is an example of code that uses a type cast
expression:
double number = 3.7;
int val;
val = static_cast<int>(number);
31
• The number inside the parentheses after the word setw
specifies the field width for the value immediately
following it.
• The field width is the minimum number of character
positions, or spaces, on the screen to print the value in.
• In the example above, the number 23 will be displayed in
a field of 5 spaces. Since 23 only occupies 2 positions on
the screen, 3 blank spaces will be printed before it.
• Because the number appears on the right side of the field
with blank spaces “padding” it in front, it is said to be
right-justified.
• setw only specifies the minimum number of positions in
the print field. Any number larger than the minimum will
cause cout to override the setw value
32
Random Numbers
• Random numbers are useful for lots of different
programming tasks.
• The C++ library has a function, rand() , that you can use
to generate random numbers. (The rand() function
requires the cstdlib header file.) The number returned
from the function is an int . Here is an example of its
usage:
y = rand();
• If you wish to limit the range of the random number,
use the following formula:
y = (rand() % ( maxValue − minValue + 1)) + minValue ;
33
• They will appear to be random, but each time the program runs,
the same values will be generated.
• In order to randomize the results of rand() , the srand() function
must be used. srand() accepts an unsigned int argument, which
acts as a seed value for the algorithm.
• By specifying different seed values, rand() will generate different
sequences of random numbers.
• A common practice for getting unique seed values is to call the
time function, which is part of the standard library. The time
function returns the number of seconds that have elapsed since
midnight, January 1, 1970.
• The time function requires the ctime header file, and you pass 0 as
an argument to the function
35