0% found this document useful (0 votes)
29 views

Sas14 Bes043

SAS14-BasS043

Uploaded by

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

Sas14 Bes043

SAS14-BasS043

Uploaded by

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

BES 043: Computer Fundamentals and Programming

Student Activity Sheet #14

Name: Class number:


Section: Schedule: Date:

Lesson title: C Strings Materials:


Lesson Objectives: At the end of the Computer, C++ Compiler
lesson the students will be able to References:
1. Write a program that uses any C C++ programming: from problem analysis to program design
string function. 5th ed. by Malik, D.S. 2011 Australia: Cengage Learning
Fundamentals of Programming C++ by Richard L. Halterman
School of Computing Southern Adventist University 2018

Productivity Tip: When handling a lot of data, it’s better to group them by name and purpose!

A. LESSON PREVIEW/REVIEW
1) Introduction (2 mins)
Topic: C Strings
Lesson connection and relevance to the students: Computers can manipulate numbers but
sometimes it’s fun if we can let the computers manipulate characters or strings also.
Learning targets: C String functions.
2) Activity 1: What I Know Chart, part 1 (3 mins)
Write in the first column what you know about the given questions in the second column below.
The third column is left blank at this time.

What I Know Questions: What I Learned (Activity 4)


1. What is a C string?

2. What can we do with C strings?

3. What are the C string


functions?

B. MAIN LESSON
1) Activity 2: Content Notes (13 mins)
Figure 11.13 Physical layout of a C string
C Strings
A string is a sequence of characters. C and C++ implement strings as arrays of char. The C++ language
additionally supports string objects. In the C language, the only option is a char array. We use the term C string
to refer to an array of characters as used in the C language. In this section, any mention of the term string refers
to a C string.
A string is an array of characters. A string literal is a sequence of characters enclosed within quotation
marks, as in
cout << "Howdy!\n";
All proper C strings are null terminated. This means the last character in the array is ASCII zero, which
C++ represents by the character literal '\0'. Figure 11.13 shows the physical layout of the string "Howdy!" in
memory.

This document is the property of PHINMA EDUCATION


BES 043: Computer Fundamentals and Programming
Student Activity Sheet #14

Name: Class number:


Section: Schedule: Date:

Since strings are actually arrays, care must be taken when using string variables:
• Enough space must be reserved for number of characters in the string, including the null terminating
character.
• The array of characters must be properly null terminated.
The following code fragment is safe and acceptable:
char *word = "Howdy!";
cout << word << '\n';
The variable word is declared to be a pointer to a character, and it is initialized to point to a string literal.
The following code fragment is less safe:
char word[256];
cin >> word;
The string word can hold 255 viable characters plus the null terminator. If the user types in relatively short
words (length less than 255 characters), there is no problem. If at any time the user types in more characters
than will fit in the word array, the executing program will have a problem. The problem is known as a buffer
overrun. In the best case, buffer overruns lead to buggy programs. In the worst case, clever users can exploit
buffer overruns to compromise software systems. Buffer overruns are always logic errors and you should take
great care to avoid them.
The following code provides a safe way to get user input:
char word[10];
fgets(word, 10, stdin);
cout << word << '\n';
The fgets function is a standard C function. The second parameter specifies the maximum length of the
string, including the terminating null character, that will be
placed in the string word. The last argument, stdin is a C
construct related to the C++ object std::cin. In order to use
fgets within a program you must include the <cstdio>
header.
The following code begs for disaster:
char *word;
cin >> word;
In this case word points to a random location in
memory (it is uninitialized), and the code allocates no buffer
to receive the input characters from std::cin. The program’s
behavior executing this code is undefined, but it likely will
lead to the program crashing. Insidiously, depending on
how the operating system manages memory, the program
may run fine much of the time and crash only rarely.
Regardless, the program contains a serious bug.
When passing an array to a function a caller must
provide the size of the array so that the function may
process the array properly. Since C strings are null
terminated, such size information is not necessary. The
find_char function in Listing 11.21 (findchar.cpp) determines if a particular character is present in a string.

This document is the property of PHINMA EDUCATION


BES 043: Computer Fundamentals and Programming
Student Activity Sheet #14

Name: Class number:


Section: Schedule: Date:

The output of Listing 11.21 (findchar.cpp) is


The find_char function in Listing 11.21 (findchar.cpp) uses pointer
notation to traverse the string. It does not need to know in advance the
number of characters in the string because it starts at the beginning and
keeps scanning each character in turn until it finds the character it is
looking for or encounters the null terminating character.
Recall from Section 5.1 that for Boolean conditions C++ treats a zero
value as false and any non-zero value as true. Because of such a loose
interpretation of Boolean expressions, we can write the find_char function
from Listing 11.21 (findchar.cpp) more compactly as the following:
char find_char(const char *s, char ch) {
// Scan until we see the null character or the character
// we seek
while (*s != '\0' && *s != ch)
s++; // Advance to the next position within the string
return *s; // Null character = false, any other is true
}
The only way out of the loop is to scan the null terminating character
or the character sought. Here, if the loop encounters the null terminating
character, it exits and returns that null character. The null character is
simply ASCII zero—Boolean false. If the loop locates the sought character, it exits and returns that character
which will not be ASCII zero. Any character except the null character has an ASCII value greater than zero;
therefore, the calling code interprets the returned character as Boolean true.
Most routines that process strings depend on the strings to be null terminated in order to work properly.
Some standard C string functions include
• int strlen(const char *s) returns the number of characters in string s, not including the null terminator.
• char *strcpy(char *s, const char *t) copies the contents of string t into string s up to and including the null
terminator; s must point to a buffer large enough to hold all the characters of C string t.
• char *strncpy(char *s, const char *t, unsigned n) works like strcpy but copies a maximum of n characters; s
must point to a buffer that can hold at least n characters.
• int strcmp(const char *s, const char *t) compares two strings for lexicographic (dictionary) ordering. The
function returns an integer less than zero if s appears lexicographically before t. The function returns an
integer greater than zero if s appears lexicographically after t. The function returns zero if the two strings are
identical.
The following code fragment
cout << strcmp("ABC", "XYZ") << '\n';
cout << strcmp("XYZ", "ABC") << '\n';
cout << strcmp("ABC", "ABC") << '\n';
prints

• int strncmp(const char *s, const char *t, int n) compares the first n characters of two strings for
lexicographic (dictionary) ordering. The function returns an integer less than zero if the first n characters of s
appear lexicographically before the first n characters of t; that is, s would appear before t is a dictionary. The

This document is the property of PHINMA EDUCATION


BES 043: Computer Fundamentals and Programming
Student Activity Sheet #14

Name: Class number:


Section: Schedule: Date:

function returns an integer greater than zero if the first n characters of s appear lexicographically after the first n
characters of t. The function returns zero if the first n characters of the two strings are identical.

2) Activity 3: Skill-building Activities (with answer key) (18 mins + 2 mins checking)
1. Write a simple password program. The password is “Hi”. The program will only check the password
once. It will display “Password granted!” if the password is correct or else it will display “Password
denied!”. Use any C string functions available.
2. Upgrade the program in the number 1. The password program will have three trials in entering the
password if it is wrong. If the password has been entered incorrectly the first and second time, it will
display “Wrong password! Try again…”.

3) Activity 4: What I Know Chart, part 2 (2 mins)


{This serves as the student’s review and summary of what was learned from the session.}
Monitor how your knowledge has changed by reviewing the questions in the What I Know Chart from
Activity 1 and write your answers to the questions based on what you now know in the third column of
the chart.
Activity 5 Set B:
4) Activity 5: Check for Understanding (5 mins)
Matching type: (Write the letter a) copies the contents of string t into string s up
before each number) to and including the null terminator; s must
Set A: point to a buffer large enough to hold all the
1. int strlen(const char *s) characters of C string t.
2. char *strcpy(char *s, const char *t) b) compares the first n characters of two strings
3. char *strncpy(char *s, const char *t, unsigned n) for lexicographic (dictionary) ordering.
4. int strcmp(const char *s, const char *t) c) works like strcpy but copies a maximum of n
5. int strncmp(const char *s, const char *t, int n) characters; s must point to a buffer that can
hold at least n characters.
d) returns the number of characters in string s,
not including the null terminator.
e) compares two strings for lexicographic
(dictionary) ordering.
C. LESSON WRAP-UP
1) Activity 6: Thinking about Learning (5 mins)
Mark the place in the work tracker which is simply a visual to help you track how much work you have
accomplished and how much work there is left to do. This tracker will be part of your activity sheet.

To develop habits on thinking about learning, answer the questions below about your learning
experience.
Three things you learned:
1.
2.

This document is the property of PHINMA EDUCATION


BES 043: Computer Fundamentals and Programming
Student Activity Sheet #14

Name: Class number:


Section: Schedule: Date:

3.

Two things that you’d like to learn more about:


1.
2.

One question you still have:


1.
FAQs
1.) Does a C string function strcmp() and strncmp() strict with lower and upper case letters also? Answer: Yes.

2.) Since a C string uses a pointer, can the reference variable be applicable to C string data?
Answer: Yes.

This document is the property of PHINMA EDUCATION

You might also like