string

COMS 261
Computer Science I
Title: C++ Fundamentals
Date: September 15, 2004
Lecture Number: 11
1
Announcements
• Read 4.1 – 4.6
• Homework
2
Review
• Standard data types
– Strings (not part of C++, but are common)
– Real (float)
• Names
• Precedence
3
Outline
• Assignment Statement
• const
• Non-fundamental Types
– string
4
Nonfundamental Types
• Nonfundamental as they are additions to the
language
• C++ permits definition of new types and classes
– A class is a special kind of type
• Class objects typically have
– Data members that represent attributes and values
– Member functions for object inspection and
manipulation
– Members are accessed using the selection operator
j = s.size();
selection operator
Nonfundamental Types
• Libraries often provide special-purpose types
and classes
• Programmers can also define their own types
and classes
• Examples
– Standard Template Library (STL) provides class
string
– Class string
• Used to represent a sequence of characters as a single
object
Class string
• Some definitions
string
string
string
string
string
name = "Joanne";
decimalPoint = ".";
empty = "";
copy = name;
question = '?'; // illegal
7
Nonfundamental Types
• To access a library use a preprocessor
directive to add its definitions to your
program file
#include <string>
8
Nonfundamental Types
• The using statement makes syntax less
clumsy
– Without it
std::string s = "Sharp";
std::string t = "Spiffy";
– With it
using namespace std; //std contains string
string s = "Sharp";
string t = "Spiffy";
9
Class string
• Some string member functions
– size() determines number of characters in
the string
string Saying = "Rambling with Gambling";
cout << Saying.size() << endl;
// 22
– substr() determines a substring (Note first
position has index 0)
string Word = Saying.substr(9, 4); // with
10
Class string
– find() computes the position of a
subsequence
int j = Saying.find("it");
int k = Saying.find("its");
// 10
// ?
11
Class string
• Auxiliary functions and operators
– getline() extracts the next input line
string Response;
cout << "Enter text: ";
getline(cin, Response, '\n');
cout << "Response is \"" << Response
<< "\"” << endl;
– Example run
Enter text: Want what you do
Response is "Want what you do"
12
Class string
• Auxiliary operators
– + string concatenation
string
string
string
string
part1
part2
part3
all =
= "Me";
= " and ";
= "You";
part1 + part2 + part3;
– += compound concatenation assignment
string thePlace = "Brooklyn";
thePlace += ", NY";
13
#include <iostream>
using namespace std;
int main() {
cout << "Enter the date in American format: "
<< "(e.g., January 1, 2001) : ";
string Date;
getline(cin, Date, '\n');
int i = Date.find(" ");
string Month = Date.substr(0, i);
int k = Date.find(",");
string Day = Date.substr(i + 1, k - i - 1);
string Year = Date.substr(k + 2, Date.size() - 1);
string NewDate = Day + " " + Month + " " + Year;
cout << "Original date: " << Date << endl;
cout << "Converted date: " << NewDate << endl;
return 0;
}
14
Boolean Algebra
• Logical expressions have the one of two
values - true or false
– A rectangle has three sides
– The instructor has a pleasant smile
• The branch of mathematics is called Boolean
algebra
– Developed by the British mathematician George
Boole in the 19th century
• Three key logical operators
– And, Or, Not (unary operator)
15
Boolean Algebra
• Truth tables
– Lists all combinations of operand values and
the result of the operation for each
combination
• Example
P
False
False
True
True
Q
False
True
False
True
P and Q
False
False
False
True
16
Boolean Algebra
• Or truth table
P
Q
False
False
True
True
P or Q
False
True
False
True
False
True
True
True
• Not truth table (unary operator)
P
False
True
not P
True
False
17
Boolean Algebra
• Can create complex logical expressions by
combining simple logical expressions
– not (P and Q)
• A truth table can be used to determine when a
logical expression is true
P
False
False
True
True
Q
False
True
False
True
P and Q
False
False
False
True
not (P and Q)
True
True
True
False
18
A Boolean Type
• C++ contains a type named bool
• Type bool has two symbolic constants
– true, false
• Boolean operators
– The and operator is &&
– The or operator is ||
– The not operator is !
• Warning
– & and | are also operators so be careful
what you type
19
A Boolean Type
• Example logical expressions
bool
bool
bool
bool
bool
bool
p
q
r
s
t
u
=
=
=
=
=
=
true;
false;
true;
(P && Q);
((!Q) || R);
!(R && (!Q));
20
Relational Operators
• Equality operators
–
–
==
!=
• Examples
– int i = 32;
– int k = 45;
– bool q = (i == k);
– bool r = (i != k);
21
Relational Operators
• Ordering operators
– <
–
–
–
>
>=
<=
• Examples
• int i = 5;
• int k = 12;
• bool p = (i
• bool q = (k
• bool r = (i
• bool s = (k
< 10);
> i);
>= k);
<= 12);
22
Operator Precedence Revisited
• Precedence of operators (from highest to
lowest)









Parentheses
Unary operators
Multiplicative operators
Additive operators
Relational ordering
Relational equality
Logical and
Logical or
Assignment
23
Operator Precedence Revisited
• Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
Yuck! Do not write expressions like this!
24
Operator Precedence Revisited
• Consider
5 * 15 + 4 == 13 && 12 < 19 || !false == 5 < 24
• Is equivalent to
((((5 *15) + 4) == 13) && (12 < 19)) || (!false) == (5 < 24))
25
Conditional Constructs
• Provide
– Ability to control whether a statement list is
executed
• Two constructs
– If statement
• if
• if-else
• if-else-if
– Switch statement
• Left for reading
26
The Basic If Statement
• Syntax
if (Expression)
Action
• If the Expression is true
then execute Action
• Action is either a single
statement or a group of
statements within
braces
Expression
true
false
Action
27
Example
if (Value < 0) {
Value = -Value;
}
If Value is less than
zero then we need to
update its value to
that of its additive
inverse
Is our number negative?
Value < 0
true
Value = -Value
false
If Value is not less
than zero then our
number is fine as is
Our number is
now definitely
nonnegative
28
Sorting Two Numbers
cout << "Enter two integers: ";
int value1;
int value2;
cin >> value1 >> value2;
if (value1 > value2) {
int rememberValue1 = value1;
value1 = value2;
value2 = rememberValue1;
}
cout << "The input in sorted order: "
<< value1 << " " << value2 << endl;
29
Semantics
Are the numbers
out of order
Rearrange value1
and value2 to
put their values
in the proper
order
value2 < value1
fa lse
true
int rememberValue1 = value1
value1 = value2
value2 = rememberValue1
The numbers were
rearranged into the
proper order
The numbers were
initially in order
The numbers are in
order
30
What is the Output?
int m =
int n =
if (m <
++m;
++n;
cout <<
5;
10;
n)
" m = " << m << " n = " n << endl;
31
The If-Else Statement
• Syntax
if (Expression)
Action1
else
Action2
• If Expression is true then execute
Action1 otherwise execute Action2
if (v == 0) {
cout << "v is 0";
}
else {
cout << "v is not 0";
}
Expression
true
false
Action1
Action2
32
Finding the Max
cout << "Enter two integers: ";
int value1;
int value2;
cin >> value1 >> value2;
int max;
if (value1 < value2) {
max = value2;
}
else {
max = value1;
}
cout << "Maximum of inputs is: " << max << endl;
33
Finding the Max
Is Value2 larger than Value1
Yes, it is . So Value2 is
larger than Value1. In
this case, Max is set
to Value2
Value1 < Value2
true
Max = Value2
Either case, Max is set
correctly
No, its not. So Value1
is at least as large as
Value2. In this case,
Max is set to Value1
false
Max = Value1
34
Selection
• It is often the case that depending upon the
value of an expression we want to perform a
particular action
• Two major ways of accomplishing this choice
– if-else-if statement
• if-else statements “glued” together
– Switch statement
• An advanced construct
35
An If-Else-If Statement
if (nbr < 0){
cout << nbr << " is negative" << endl;
}
else if (nbr > 0) {
cout << nbr << " is positive" << endl;
}
else {
cout << nbr << " is zero" << endl;
}
36
A Switch Statement
switch (ch) {
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
cout << ch << " is a vowel" << endl;
break;
default:
cout << ch << " is not a vowel" << endl;
}
37
Example
cout << "Enter simple expression: ";
int left;
int right;
char operator;
cin >> left >> operator >> right;
cout << left << " " << operator << " " << right << " = ";
switch (Operator) {
case '+' : cout << left + right << endl; break;
case '-' : cout << left - right << endl; break;
case '*' : cout << left * right << endl; break;
case '/' : cout << left / right << endl; break;
default: cout << "Illegal operation" << endl;
}
38