C++ C++ for for Engineers and Engineers and Scientists Scientists Second Edition Second Edition Chapter 7 Completing the Basics
C++ C++ forfor Engineers and ScientistsEngineers and Scientists
Second EditionSecond Edition
Chapter 7Completing the Basics
C++ for Engineers and Scientists, Second Edition 2
ObjectivesObjectives
• Exception Handling• The string Class• Character Manipulation Methods• Input Data Validation• Namespaces and Creating a Personal Library• Common Programming Errors
C++ for Engineers and Scientists, Second Edition 3
Exception HandlingException Handling
• Exception: a value, variable, or object that contains information about the error that occurred
• Exception handler: code designed to deal with exceptions
• Throwing an exception: the process of generating and passing an exception at the point where the error was detected
C++ for Engineers and Scientists, Second Edition 4
Exception Handling (continued)Exception Handling (continued)
• Two basic types of errors, caused by– Inability to obtain a required resource
– Flawed data
• Catch an exception: receive a thrown exception and process it
• Try and catch keywords are used for throwing and catching exceptions
C++ for Engineers and Scientists, Second Edition 5
Exception Handling (continued)Exception Handling (continued)
• try keyword starts the exception handling block of code
• Statements that may throw an exception are placed within the braces
• One or more catch blocks follow the try block• Each catch block catches a unique exception
type, identified in parentheses• At least one catch block is required for a try
block
C++ for Engineers and Scientists, Second Edition 6
Exception Handling (continued)Exception Handling (continued)
Syntax:
C++ for Engineers and Scientists, Second Edition 7
Exception Handling (continued)Exception Handling (continued)
C++ for Engineers and Scientists, Second Edition 8
The The stringstring Class Class• Class: a user-created data type that defines a
valid set of data values and a set of operations that can be used on them
• Object: storage area declared for a class• string class permits string literals• String literal: any sequence of characters
enclosed in double quotation marks; also called string value, string, constant
Figure 7.1 The storage of a string as a sequence of characters.
C++ for Engineers and Scientists, Second Edition 9
The The stringstring Class (continued) Class (continued)
• string class provides functions for declaring, creating, and initializing a string
• Methods: functions in a class• Constructor: the method which creates and
initializes a string object• string header file is required to use the string class
C++ for Engineers and Scientists, Second Edition 10
The The stringstring Class (continued) Class (continued)
C++ for Engineers and Scientists, Second Edition 11
The The stringstring Class (continued) Class (continued)
C++ for Engineers and Scientists, Second Edition 12
The The stringstring Class (continued) Class (continued)
• Character positions within a string are numbered starting with zero
C++ for Engineers and Scientists, Second Edition 13
The The stringstring Class (continued) Class (continued)
• Strings can be input from the keyboard and displayed on the screen using cout, cin, and getline
• getline continuously accepts and stores characters from the keyboard until the terminating key is pressed
• If the last argument is omitted, the Enter key will terminate the inputSyntax:
getline(cin, strObj, terminatingChar)
C++ for Engineers and Scientists, Second Edition 14
The The stringstring Class (continued) Class (continued)
C++ for Engineers and Scientists, Second Edition 15
The The stringstring Class (continued) Class (continued)
• Using cin and getline inputs together in the same program may cause problems
• cin accepts the input, but leaves the newline code from the Enter key in the buffer, which will be picked up by the getline as the end of its input
C++ for Engineers and Scientists, Second Edition 16
The The stringstring Class (continued) Class (continued)
• Three possible solutions to this problem:– Do not use cin and getline inputs in the
same program
– Follow the cin input with cin.ignore()
– Accept the Enter key into a character variable and then ignore it
C++ for Engineers and Scientists, Second Edition 17
The The stringstring Class (continued) Class (continued)
• string class provides many methods for manipulating strings, including– length: returns the length of the string– at: returns the character at the specified index– compare: compares two strings– empty: tests if the string is empty– erase: removes characters from the string– find: returns the index of the first occurrence of
a string in an object
C++ for Engineers and Scientists, Second Edition 18
The The stringstring Class (continued) Class (continued)
• string class methods (continued):– insert: inserts one string into another string at
the specified index– replace: replaces characters in an object at
the specified index– substr: returns a portion of a string– swap: swaps characters in a string with a
specified object
• Concatenation operator (+) combines two strings
C++ for Engineers and Scientists, Second Edition 19
The The stringstring Class (continued) Class (continued)
• All relational operators may be used to compare strings; ASCII or UNICODE code values are used for comparison
Figure 7.5 The initial strings used in Program 7.6.
C++ for Engineers and Scientists, Second Edition 20
The The stringstring Class (continued) Class (continued)
C++ for Engineers and Scientists, Second Edition 21
The The stringstring Class (continued) Class (continued)
C++ for Engineers and Scientists, Second Edition 22
The The stringstring Class (continued) Class (continued)• Example: Inserting characters in a string
string str = “This cannot be”;
str.insert(4, “ I know”);
C++ for Engineers and Scientists, Second Edition 23
The The stringstring Class (continued) Class (continued)
• Example: Replacing characters in a string
str.replace(12, 6, “to”);
str += “ correct”;
C++ for Engineers and Scientists, Second Edition 24
The The stringstring Class (continued) Class (continued)
C++ for Engineers and Scientists, Second Edition 25
Character Manipulation MethodsCharacter Manipulation Methods
• Character manipulation methods require the header file string or cctype
• character class provides methods for character manipulation, including– Character type detection: isalpha, isalnum, isdigit, isspace, isprint, isascii, isctrl, ispunct, isgraph, isupper, islower
– Character case conversion: toupper, tolower
C++ for Engineers and Scientists, Second Edition 26
Character Manipulation Methods Character Manipulation Methods (continued)(continued)
C++ for Engineers and Scientists, Second Edition 27
Character Manipulation Methods Character Manipulation Methods (continued)(continued)
• Basic character I/O methods, requiring the header file cctype, include– cout.put: put a character on the output stream– cin.get: extract a character from the input
stream– cin.peek: assign the next character from the
input stream to a variable without extracting it– cin.putback: pushes a character back onto
the input stream– cin.ignore: ignores input characters
C++ for Engineers and Scientists, Second Edition 28
Character Manipulation Methods Character Manipulation Methods (continued)(continued)
• When a character is requested after the user has already input some other data, get() method may pick up the Enter key instead of the new data
• Two ways to solve this problem:– Use a cin.ignore() after the cin.get()– Accept Enter key and do not process it
C++ for Engineers and Scientists, Second Edition 29
Character Manipulation Methods Character Manipulation Methods (continued)(continued)
C++ for Engineers and Scientists, Second Edition 30
Input Data ValidationInput Data Validation
• User-input validation includes checking each entered character to ensure it is the expected data type
• Can accept user input as a string, and then check each character for proper typeExample: input of an integer number
– Data must contain one or more characters
– If the first character is a + or -, there must be at least one digit
– Only digits from 0 to 9 are acceptable
C++ for Engineers and Scientists, Second Edition 31
Namespaces and Namespaces and Creating a Personal LibraryCreating a Personal Library
• Namespaces provide the ability to group a set of classes, objects, or functions under a nameSyntax:
namespace name
{
functions and/or classes in here
} // end of namespace
• A file can contain more than one namespace
C++ for Engineers and Scientists, Second Edition 32
Namespaces and Creating Namespaces and Creating a Personal Library (continued)a Personal Library (continued)
• To use the namespace file, add a preprocessor directive containing the namespace path to the program Example:
#include <c:\\mylibrary\\dataChecks>
using namespace dataChecks;
• If more than one namespace is in the file, only the requested namespace will be loaded
C++ for Engineers and Scientists, Second Edition 33
Common Programming ErrorsCommon Programming Errors
• Failure to include the string header file when using string class objects
• Failure to remember that the newline character, ‘\n’, is a valid data input character
• Failure to convert a string class object using the c_str() method when converting to numerical data types
C++ for Engineers and Scientists, Second Edition 34
SummarySummary
• String literal: any sequence of characters enclosed in double quotation marks
• string class can be used to construct a string• string class objects are used when
comparing, searching, examining, or extracting a substring, or replacing, inserting, or deleting characters
• cin object terminates input when a blank is encountered
C++ for Engineers and Scientists, Second Edition 35
Summary (continued)Summary (continued)
• getline() method can be used for string class data input
• cout object can be used to display string class strings