CS102 Introduction to Computer Programming

Download Report

Transcript CS102 Introduction to Computer Programming

CS102
Introduction to Computer
Programming
Chapter 10 Characters and Strings
Topics for Discussion
•
•
•
•
•
•
•
Character Testing
Character Case Conversion
Review of the Internal Storage of Strings
Strings Stored in Arrays
Library Functions for Working With Arrays
String Numeric Conversion Functions
Writing String Handling Functions
Character Testing
• In C a macro is a #define that takes arguments
– It behaves like a function call
– When a macro is called it is inserted directly into
the program
– Replaced in C++ by the inline function
• Include the ctype.h header for the following
macros:
Concept - The C++ Library provides macros for testing
characters
#include <ctype.h>
•
•
•
•
•
•
isalpha returns True if a letter of the alphabet
isalnum returns True if a letter or number 0-9
isdigit
returns True if a number 0-9
islower returns True if a lower case letter
isprint
returns True if a printable character
ispunct returns True if a printable character other
than a letter or digit or space
• isupper returns True if a uppercase letter
• isspace returns True if a white space character
– space
– newline
''
'\n'
– vertical tab
– tab
'\v '
'\t'
/* This program demonstrates some of the
character testing macros. */
#include <iostream.h>
#include <ctype.h>
void main(void)
{
char Input;
cout << "Enter any character: ";
cin.get(Input);
cout << "The character you entered is: " << Input
<< endl;
cout << "Its ASCII code is: " << int(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";
}
Program 10-1
Program Output
Enter any character: A [Enter]
The character you entered is: A
Its ASCII code is: 65
That's an alphabetic character.
The letter you entered is
uppercase.
Program Output
Enter any character: 7
[Enter]
The character you entered is:
7
Its ASCII code is: 55
That's a numeric digit.
Program 10-2
/* This program tests a customer
number to determine if it is in the
proper format.*/
#include <iostream.h>
#include <ctype.h>
// Function prototype
int TestNum(char []);
void main(void)
{
char Customer[8];
cout << "Enter a customer number
in the form ";
cout << "LLLNNNN\n";
cout << "(LLL = letters and NNNN =
numbers): ";
cin.getline(Customer, 8);
if (TestNum(Customer))
cout << "That's a valid
customer number.\n";
else
{
cout << "That is not the
proper format of the ";
cout << "customer
number.\nHere is an example:\n";
cout << " ABC1234\n";
}
}
Program 10-2
// Definition of function TestNum.
int TestNum(char CustNum[])
{
// Test the first three characters for letters
for (int Count = 0; Count < 3; Count++)
{
if (!isalpha(CustNum[Count]))
return 0;
}
// Test the last 4 characters for numeric digits
for (int Count = 3; Count < 7; Count++)
{
if (!isdigit(CustNum[Count]))
return 0;
}
return 1;
}
Program Output
Enter a customer number in the
form LLLNNNN
(LLL = letters and NNNN =
numbers): RQS4567 [Enter]
That's a valid customer number.
Program Output With Other
Example Input
Enter a customer number in the
form LLLNNNN
(LLL = letters and NNNN =
numbers): AX467T9 [Enter]
That is not the proper format of the
customer number.
Here is an example:
ABC1234
Character Case Conversion
• Touppper (tolower)
– accepts a single character as an argument
– if the character is lower case(upper case) it
returns the upper case(lower case) equivalent
– if is already upper case(lower case) or not a
letter the original value is returned
• Call by value. The argument is not changed
• Must include ctype.h
Concept - The C++ Library provides functions for converting a
character to upper or lower case.
Program 10-3
/* This program calculates the area of
a circle. It asks the user if he or she
wishes to continue. A loop that
demonstrates the toupper function
repeats until the user enters 'y', 'Y',
'n', or 'N'.*/
#include <iostream.h>
#include <ctype.h>
void main(void)
{
const float Pi = 3.14159;
float Radius;
char Go;
cout << "This program calculates
the area of a circle.\n";
cout.precision(2);
cout.setf(ios::fixed);
do
{
cout << "Enter the circle's
radius: ";
cin >> Radius;
cout << "The area is " << (Pi *
Radius * Radius);
cout << endl;
do
{
cout << "Calculate another?
(Y or N) ";
cin >> Go;
} while (toupper(Go) != 'Y' &&
toupper(Go) != 'N');
} while (toupper(Go) == 'Y');
}
Program Output With Example Input
This program calculates the area of a circle.
Enter the circle's radius: 10 [Enter]
The area is 314.16
Calculate another? (Y or N) b Enter]
Calculate another? (Y or N) y [Enter]
Enter the circle's radius: 1 [Enter]
The area is 3.14
Calculate another? (Y or N) n [Enter]
Internal Storage of Strings
Review
• The null character '\0' is used to terminate a
character string
• A string constant is any literal string enclosed
in " "
– it has its own storage location just like the
variables of an array
• A string stored in an array can be processed
using standard subscript notation.
Concept - In C++, a string is a sequence of characters stored in
consecutive memory locations, terminated by a null character.
Program 10-5
/* This program cycles through a
character array, displaying each
element until a null terminator is
encountered.*/
#include <iostream.h>
void main(void)
{
char Line[80];
int Count = 0;
cout << "Enter a sentence of no
more than 79 characters:\n";
cin.getline(Line, 80);
cout << "The sentence you entered
is:\n";
while (Line[Count] != '\0')
{
cout << Line[Count];
Count++;
}
}
Program Output
Enter a sentence of no more than 79
characters:
C++ is challenging but fun! [Enter]
The sentence you entered is:
C++ is challenging but fun!
String Manipulators
Review
• cin can be used to input a character string
with no white space characters
cin >>last_name; Edwards Enter
• cin.getline can be used input a character
string with spaces into an array
cin.getline(name,20); Daniel Edwards Enter
• cin.get can be use to input a single character
of any type
cin.get(ch);
Enter
Strings Stored in Arrays
• There is no data type for string variables.
– Character strings can be stored in character
arrays
• There is no boundary checking for Strings.
– Be sure the array is large enough to hold the
null terminator
• An array name with no [ ] and subscripts is
the address of the first element of the array.
array = = &array[0] is true
• A string stored in an array can be processed
using standard subscript notation.
Library Functions for Working
With Character Arrays
strlen
returns the length of a string not including the null
terminator
int len; char Name[] ="Francis";
len = strlen (Name); cout << len;
strcat
7
appends the contents of one string to another
char First[13] ="Francis", Second [] = "Bacon" ;
strcat (First, Second);
cout <<First <<" "<<Second;
FrancisBacon Bacon
strcpy
copies one string to another
char First[14] = "Francis", Name [] = "Francis Bacon"
strcpy (First, Name)
cout <<First <<" " <<Name;
Francis Bacon Francis Bacon
Library Functions for Working
With Character Arrays
strncpy copies a specified number of characters from string2
to string1
char First [8], Name[] = "Francis Bacon";
strncpy (first, Name, 7);
cout << First <<" " <<Name;
Francis Francis Bacon
strcmp
compares the contents of two strings.
returns 0 if string2 = = string1
returns negative if string2 is > string 1
returns positive if string2 is < string 1
strstr
searches a string for the location of another string
char Name[] = "Francis Bacon", Second[] = "Bacon" ;
cout <<strstr (Name, Second);
Bacon
(because cout displays the string if given an address)
Program 10-6
// This program uses the strstr function
to search an array of strings for a
name.*/
#include <iostream.h>
#include <string.h> // For strstr
void main(void)
{
char Prods[5][27] =
{"TV327 31 inch Television",
"CD257 CD Player",
"TA677 Answering Machine",
"CS109 Car Stereo",
"PC955 Personal Computer"};
char LookUp[27], *StrPtr = NULL;
int Index;
cout << "\tProduct Database\n\n";
cout << "Enter a product number
to search for: ";
cin.getline(LookUp, 27);
for (Index = 0; Index < 5; Index++)
{
StrPtr = strstr(Prods[Index],
LookUp);
if (StrPtr != NULL)
break;
}
if (StrPtr == NULL)
cout << "No matching
product was found.\n";
else
cout << Prods[Index] <<
endl;
}
Program Output
Product Database
Enter a product to search for: CD257 [Enter]
CD257 CD Player
Program Output With Example Input
Product Database
Enter a product to search for: CS [Enter]
CS109 Car Stereo
Program Output With Other Example Input
Product Database
Enter a product to search for: AB [Enter]
No matching product was found.
Differences Between
Strings and Numbers
• There is a difference between numbers stored as strings and
numbers stored as numeric values.
– A character string of digits isn't a number but a series of ASCII
codes.
• mathematical operations can not be performed on it
– It uses 1 byte of memory for each digit.
• an int data type takes 2 bytes for the whole number
• The C++ library provides functions for converting a string
representation of a number to a numeric data type and viceversa.
10.5 String/Numeric Conversion
Functions
• The C++ library provides functions for
converting a string representation of a
number to a numeric data type, and viceversa.
• The functions in this section require the
stdlib file to be included.
String Numeric Conversion
Functions
atoi
atol
atof
itoa
converts a string of digits into an
integer .
converts a string of digits into a long
integer.
converts a string of digits into a
floating point number.
converts an integer into a character
string and stores it in an array.
Caution: make sure the array is large enough to hold all
the characters plus the null terminator.
Program 10-7
while ((strcmp(Input, "Q") !=
0)&&(strcmp(Input, "q") != 0))
{
Total += atoi(Input); // Keep
#include <iostream.h>
a running total
#include <string.h> // For strcmp
Count++; // Keep track of
#include <stdlib.h> // For atoi
how many numbers entered
cout << "Enter the next
void main(void)
number or Q to quit: ";
{
cin.getline(Input, 20);
char Input[20];
}
int Total = 0, Count = 0;
if (Count != 0)
float Average;
{
cout << "This program will average
Average = Total / Count;
a series of numbers.\n";
cout << "Average: " <<
cout << "Enter the first number or Q
Average << endl;
to quit: ";
}
cin.getline(Input, 20);
}
// This program demonstrates the
strcmp and atoi functions.
Program Output
This program will average a series of numbers.
Enter the first number or Q to quit: 74 [Enter]
Enter the next number or Q to quit: 98 [Enter]
Enter the next number or Q to quit: 23 [Enter]
Enter the next number or Q to quit: 54 [Enter]
Enter the next number or Q to quit: Q [Enter]
Average: 62
The C++ string Class
• Offers “ease of programming” advantages
over the use of C-strings
• Need to #include the string header file
Program 10-12
// This program demonstrates the C++ string class.
#include <iostream>
#include <string> // Required for the string class
using namespace std;
void main(void)
{
string movieTitle;
string name("William Smith");
movieTitle = "Wheels of Fury";
cout << "My favorite movie is " << movieTitle << endl;
}
Program output
My favorite movie is Wheels of Fury
Program 10-13: Using cin with
a string object
// This program demonstrates how cin can read a string into
// a string class object.
#include <iostream>
#include <string>
using namespace std;
void main(void)
{
string name;
cout << "What is your name? " << endl;
cin >> name;
cout << "Good morning " << name << endl;
}
Program Output With Example
Input
What is your name? Peggy
Good morning Peggy
Reading a line of input into a
string class object
• Use the getline function to read a line of
input, with spaces, into a string object.
Example code:
string name;
cout << “What is your name? “;
getline(cin, name);
Comparing and Sorting string
Objects
• You may use the relational operators to
compare string objects:
<
>
<=
>=
==
!=
Program 10-14
// This program uses the == operator to compare the string entered
// by the user with the valid stereo part numbers.
#include <iostream>
#include <string>
using namespace std;
void main(void)
{
const float aprice = 249.0, bprice = 299.0;
string partNum;
cout << "The stereo part numbers are:\n";
cout << "\tBoom Box, part number S147-29A\n";
cout << "\tShelf Model, part number S147-29B\n";
cout << "Enter the part number of the stereo you\n";
cout << "wish to purchase: ";
cin >> partNum;
cout << fixed << showpoint << precision(2);
Program 10-14 (continued)
if (partNum == "S147-29A")
cout << "The price is $" << aprice << endl;
else if (partNum == "S147-29B")
cout << "The price is $" << bprice << endl;
else
cout << partNum << " is not a valid part number.\n";
}
Program Output
The stereo part numbers are:
Boom Box, part number S147-29A
Shelf Model, part number S147-29B
Enter the part number of the stereo you
wish to purchase: S147-29A [Enter]
The price is $249.00
Other Ways to Declare string
Objects
Declaration Example
Description
string address
Declares an empty string
object named address.
name is a string object
initialized with “Bill Smith”
person1 is initialized with a
copy of person2. person2
may be either a string object
or a char array.
string name(“Bill Smith”);
string person1(person2);
See Table 10-8 (page 589) for more examples.
Table 10-10 Other Supported
Operators
>>
Extracts characters from a stream and inserts
them into a string. Characters are copied
until a whitespace or the end of the string is
encountered.
<<
Inserts a string into a stream.
=
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.
[]
Implements array-subscript notation, as in
name[x]. A reference to the character in the x
position is returned.
Program 10-17
// This program demonstrates the C++ string class.
#include <iostream>
#include <string>
using namespace std;
void main(void)
{
string str1, str2, str3;
str1 = "ABC";
str2 = "DEF";
str3 = str1 + str2;
cout << str1 << endl;
cout << str2 << endl;
cout << str3 << endl;
str3 += "GHI";
cout << str3 << endl;
}
Program Output
ABC
DEF
ABCDEF
ABCDEFGHI
string class member functions
• Many member functions exist.
• See Table 10-10 (pages 592-594)