0% found this document useful (0 votes)
18 views35 pages

ENG2139 Lecture 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views35 pages

ENG2139 Lecture 4

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

ENG2139 INTRODUCTION TO ICT

Lecture 4 : Characters and C-Strings

Instructor: George ZIBA


Email: [email protected]
0976854627

George ZIBA , DEPT. of EEE, School of Engineering, UNZA


References
Our main reference text books and websites in this course are:
[1] Juan Soulie, 2007, C++ Language Tutorial
[2] Tony Gaddis, 2015, Starting out with C++ from control structures through
objects
[3] https://www.w3schools.com/cpp/

George ZIBA , DEPT. of EEE, School of Engineering, UNZA 2


Course Outline
Introduction and Basics of C++ :Syntax, Output, Comments, Structure of a program,
Variables, Data types, Constants, Basic input/output, Operators, Strings, Booleans,
Math, Conditions, Switch, While Loop, For Loop, Break/Continue, Arrays, Structures,
References, Pointers

C++ Functions: Functions, Function Parameters, Function Overloading, Recursion,


variable scope

Characters and C-Strings: Character Testing, Character Case Conversion, C-Strings,


Library Functions for Working with C-Strings, C-String/Numeric Conversion
Functions, More About the C++ string Class

C++ Classes: OOP, Classes/Objects, Class Methods, Constructors, Access Specifiers,


Encapsulation, Inheritance, Polymorphism, Files, Exceptions

George ZIBA , DEPT. of EEE, School of Engineering, UNZA 5


3
Course Requirements
Distribution of Marks
 Assignments 5%
 Labs 15%
 Test 20%
 Final Exam 60%

Required Compilers/ IDE


 CodeBlocks
 Eclipse
 Any

Time Allocation
• Lectures 2 hours/week
• Laboratory/ Tutorials 3 hours/week

George ZIBA , DEPT. of EEE, School of Engineering, UNZA 4


Character Testing
• The C++ library provides several functions for testing
characters. To use these functions you must include the
<cctype> header file.
• The C++ library provides several functions that allow you to
test the value of a character. These functions test a single
char argument and return either true or false .

char letter = 'a';


if (isupper(letter))
cout << "Letter is uppercase.\n";
else
cout << "Letter is lowercase.\n";

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.

isalnum Returns true (a nonzero number) if the


argument is a letter of the alphabet
or a digit. Otherwise it returns 0.

isdigit Returns true (a nonzero number) if the


argument is a digit from 0 through 9.
Otherwise it returns 0.

islower Returns true (a nonzero number) if the


argument is a lowercase letter.
Otherwise, it returns 0.
isupper Returns true (a nonzero number) if the
argument is an uppercase letter.
Otherwise, it returns 0.
ispunct Returns true (a nonzero number) if the
argument is a printable character
other than a digit, letter, or space.
Returns 0 otherwise
6
// This program demonstrates some character-testing functions.
#include <iostream>
#include <cctype>
using namespace std;

int main()
{
char input;

cout << "Enter any character: ";


cin.get(input);
cout << "The character you entered is: " << input << endl;
if (isalpha(input))
cout << "That's an alphabetic character.\n";
if (isdigit(input))
cout << "That's a numeric digit.\n";
if (islower(input))
cout << "The letter you entered is lowercase.\n";
if (isupper(input))
cout << "The letter you entered is uppercase.\n";
if (isspace(input))
cout << "That's a whitespace character.\n";
return 0;
}

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

• The C++ library has numerous functions for


handling C-strings. These functions perform
various tests and manipulations and require
that the <cstring> header file be included
• The strlen function accepts a pointer to a C-
string as its argument. It returns the length of
the string, which is the number of characters
up to, but not including, the null terminator.

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:

strncat(string1, string2, 10);

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

int strcmp(char *string1, char *string2);


• The function takes two C-strings as parameters (actually, pointers
to C-strings) and returns an integer result. The value of the result is
set accordingly:
1. The result is zero if the two strings are equal on a character-by-
character basis
2. The result is negative if string1 comes before string2 in
alphabetical order
3. The result is positive if string1 comes after string2 in alphabetical
order
20
C-String/Numeric Conversion Functions
• The C++ library provides functions for converting a C-string
representation of a number to a numeric data type and vice versa.
• There is a great difference between a number that is stored as a string
and one stored as a numeric value.
• The string “ 26792 ” isn’t actually a number, but a series of ASCII codes
representing the individual digits of the number.
• If a string that cannot be converted to a numeric value is passed to
any of these functions, the function’s behavior is undefined by C++.
Many compilers, however, will perform the conversion process until an
invalid character is encountered.
• For example, atoi("123x5") might return the integer 123. It is possible
that these functions will return 0 if they cannot successfully convert
their argument

21
Function Description

atoi Accepts a C-string as an argument. The function converts the


C-string to an integer
and returns that value.
Example Usage: int num = atoi("4569");

atol Accepts a C-string as an argument. The function converts the


C-string to a long integer
and returns that value.
Example Usage: long lnum = atol("500000");

atof Accepts a C-string as an argument. The function converts the


C-string to a double
and returns that value.
Example Usage: double fnum = atof("3.14159");

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

= Assigns the string on the right to the string


object on the left

+= Appends a copy of the string on the right to the


string object on the left

+ Returns a string that is the concatenation of the


two string operands

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);

• Type cast expressions are useful in situations where C++ will


not perform the desired conversion automatically.
30
Formatting Output
• The cout object provides ways to format data as it is being
displayed. This affects the way data appears on the screen.
• The way a value is printed is called its formatting. The cout
object has a standard way of formatting variables of each data
type. Sometimes, however, you need more control over the
way data is displayed.
• cout offers a way of specifying the minimum number of spaces
to use for each number. A stream manipulator, setw found in
<iomanip> headerfile, can be used to establish print fields of a
specified width. Here is an example of how it is used:
value = 23;
cout << setw(5) << value;

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

unsigned seed =time(0);


srand(seed);
cout << rand() << endl;
34
End of Lecture 4

Thank you for your attention!

35

You might also like