(LN 5-1) Review Exercises on Class

Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
(LN 5-1) Review Exercises on Class
1. Refer to the Coins class on the right:
•
There is/are ____ constructor(s).
The default constructor is: ___________.
•
Including the constructors, there are ____
member functions.
•
Among the member functions, the private
member function(s) is/are:
____________________.
•
/*Coins.cpp*/
..
/*Coins.h*/
There are ______ data members (member
variables).
•
In the main function, circle the calling object
where whose member functions are being
called.
•
In the input function, highlight the data
members of the calling object.
class Coins
{
public:
Coins(int d, int c);
Coins();
void input();
void output();
int get_dollar();
int get_cent50();
void Coins::input()
{
int d, c;
cin >> d >> c;
if (valid(d,c))
{
dollar = d;
cent50 = c;
}
}
private:
bool valid(int d, int c);
int dollar;
int cent50;
};
/*srcMain.cpp*/
..
void main()
{
Coins wallet;
cout << "Input amounts of $1 and $0.5 coins: ";
wallet.input();
cout << "The wallet has: ";
wallet.output();
cout << endl;
}
2. The following is a simplified code for "Vending Machine".
However, there are compilation errors:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
using namespace std;
class VendMach{
public:
VendMach(int tm, int tc);
int insertCoin(int x);
private:
int paid; int totalMoney; int totCokes;
};
VendMach::VendMach(int tm, int tc)
{
paid=0; totalMoney=tm;
totCokes=tc;
}
void VendMach::insertCoin(int x)
{
if (x==1 || x==2 || x==5)
paid+=x;
cout << "$" << paid << " paid\n";
}
void main()
{
//... Compiling...
}
VendingMachine.cpp
c:\code\ln5_framework.cpp(18) : error C2556: 'void VendMach::insertCoin(int)' :
overloaded function differs only by return type from 'int VendMach::insertCoin(int)'
c:\code\ln5_framework.cpp(7) : see declaration of 'VendMach::insertCoin'
c:\code\ln5_framework.cpp(18) : error C2371: 'VendMach::insertCoin' : redefinition; different basic types
c:\code\ln5_framework.cpp(7) : see declaration of 'VendMach::insertCoin'
VendingMachine - 2
error(s), 0 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
1/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
(LN 5-2) const modifier for the calling object
Date d;
‰ When we call a member function, the calling object
behaves like a call-by-reference parameter:
..
if (d.isEndOfAMonth())
cout << "It is the end of a month.";
That function may change the value of the calling object.
‰ If the member function is not supposed to change the calling object, we mark the function with const:
/* Date.h */
//The Date class
class Date
{
public:
Date();
Date(int y, int m, int d);
Add const at end of function
headers in both .h and .cpp
/* Date.cpp */
..
bool isEndOfAMonth() const;
Date next() const;
void input();
void output() const;
void set(int new_y, int new_m, int new_d);
int get_year() const;
int get_month() const;
int get_day() const;
private:
bool valid(int y, int m, int d) const;
bool isLeapYear(int y) const;
int year, int month, int day;
};
// Check whether the calling date object contains a date that's the ending day of any month
bool Date::isEndOfAMonth() const
{
if (valid(year,month,day+1))
return false;
else
return true;
}
// Return the "tomorrow" of the calling date object
Date Date::next() const
{
if (isEndOfAMonth())
if (month==12)
return Date(year+1,1,1);
else
return Date(year,month+1,1);
else
return Date(year,month,day+1);
}
..
‰ Recall that next() makes use of isEndOfMonth().
If we omit const for isEndOfMonth, most compilers will
complain. They assume isEndOfMonth will change the
value of the calling object, i.e., d.
So they think next should not call isEndOfMonth.
void main()
{
Date d, dNext;
..
dNext = d.next();
cout << "The next day is: ";
dNext.output();
}
2/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
(LN 5-3) Operator Overloading
(A) Overloading Operators
‰
An operator is just a form of a function – with a different syntax for listing its arguments
‰
E.g.
‰
x+y
: +(x,y)
- similar to add(x,y)
x==y
: ==(x,y)
- similar to equal(x,y)
Operators can be overloaded in 2 ways:
- As a friend function (We will cover this one only)
- As a member function
class Coins
{
public:
//Overloaded operators: + and ==
friend Coins operator+(const Coins &coins1, const Coins &coins2);
friend bool operator==(const Coins &coins1, const Coins &coins2);
...
private:
...
/*Coins.cpp*/
int dollar; //count of $1 coins
int cent50; //count of $0.5 coins
};
..
//Overloaded + operator for Coins
Coins operator+ (const Coins &x, const Coins &y)
{
↑ first parameter
↑ second parameter
return Coins(x.dollar+y.dollar, x.cent50+y.cent50);
}
We use these operator functions like:
Coins wallet1, wallet2;
//Overloaded == operator for Coins
bool operator== (const Coins &x, const Coins &y)
{
return (x.dollar==y.dollar && x.cent50==y.cent50);
}
if (wallet1==wallet2)
..
Coins sum;
sum = wallet1 + wallet2;
Left operand : first parameter
Right operand : second parameter
void main()
{
Coins wallet1, wallet2, sum;
cout << "Wallet 1: Input amounts of $1 and $0.5 coins: ";
wallet1.input();
cout << "Wallet 2: Input amounts of $1 and $0.5 coins: ";
wallet2.input();
if (wallet1==wallet2)
cout << "Same!\n";
else
cout << "Different!\n";
sum = wallet1+wallet2;
cout << "The sum is: ";
sum.output();
cout << endl;
Wallet 1: Input amounts of $1 and $0.5 coins: 3 2
Wallet 2: Input amounts of $1 and $0.5 coins: 7 4
Different!
The sum is: (10,6)
Press any key to continue . . .
}
3/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
Rules on overloading operators
‰ When overloading an operator, at least one argument of the resulting overloaded operator must be of a
class type.
E.g. Coins operator+(const Coins &coins1, int extraDollars);
‰ You cannot create a new operator
‰ You cannot change the number of arguments that an operator takes
‰ You cannot change the precedence of an operator
E.g., x*y + z is always interpreted as (x*y)+z
‰ The following operators cannot be overloaded:
.
::
?:
‰ The following operators can be overloaded but the syntax is different: =
[]
->
(B) Constructors for automatic type conversion
‰ Consider the example:
Coins walletA(2,1), sum;
sum = walletA+10; //Ten 1-dollars added : $2.5 + $10 = $12.5
sum.output();
‰ When the system sees the expression:
walletA + 10
it checks if + is overloaded for addition between Coins and integer.
‰ If not, it checks if there is a constructor that takes an integer and converts it to Coins.
class Coins
{
public:
//Operator +
friend Coins operator+(const Coins &coins1, const Coins &coins2);
//Constructors
Coins(int d, int c);
/*Coins.cpp*/
..
Coins(int d); // conversion constructor
Coins();
//I-O
void input();
void output() const;
private:
//Validation
bool valid(int d, int c) const;
//conversion constructor
Coins::Coins(int d)
{
if (valid(d,0))
{
dollar = d; cent50 = 0;
}
}
..
int dollar;
int cent50;
In this case, the actual story for "walletA + 10" will be:
(1) Firstly run the conversion constructor to turn 10 into a Coins object (ie. d is 10 and so the new object's
dollar equals 10 and cent50 equals 0), then
(2) run the "+" operator for adding walletA and this new Coins object.
Suggestion: Trace with the debugger: F10 and F11 to see how the conversion constructor runs!
4/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
(C) Overloading >> and <<
(1) Overloading the << operator
- Note that:
runs as:
cout << "I have " << amount;
c
d
(cout << "I have ") << amount;
- Therefore cout << "I have " should give an output stream object
That means, operator << should have the return type: ostream
Actually cout
d
So that when .. << amount runs, the
left-hand-side of << is cout.
- The stream object may be cout, and it may be some others, eg. an output-file-stream-object!!
- Actually operator << should return its first parameter.
#include <iostream>
using namespace std;
class Coins
{
( Left ) first parameter
public:
( Right ) second parameter
friend ostream& operator <<( ostream &outs, const Coins &amt );
...
};
ostream& operator <<(ostream &outs, const Coins &amt)
{
outs << "(" << amt.dollar << "," << amt.cent50 << ")";
return outs;
should be outs, not cout !!
}
** outs may not be equal to cout :
Because outs may refer to a file-stream.
- If an operator (or function) returns a stream object, we add an & like ostream
& operator <<(..)
Reason: We don't want to create a new stream object by copying, so "return-by-reference".
Then the operator will return a reference to the stream object (instead of the value of the stream object).
- Before the prototype of << (in .h), we must have the code below:
#include <iostream>
using namespace std;
Reason: the compiler has to see the "ostream" class first.
(2) Overloading the >> operator
[Your task] Choose the correct form:
† istream &operator >>(istream &ins, const Coins &amt);
† istream operator >>(istream ins, Coins amt);
† istream &operator >>(const istream &ins, const Coins &amt) const;
5/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
(LN 5-4) Cstrings
- cstring is a special type for storing strings (text, sequence of chracters)
- called "cstring" because it is inherited from the C language.
- May appear as
(i) a string constant:
e.g. cout << "OK!";
(ii) an array of characters
e.g. char s[4];
- The internal representations of (i) and (ii) are alike:
simply a sequence of characters followed by the null character ('\0' or 0)
A special character whose ASCII code is zero.
It marks the end of the cstring.
- The ASCII codes of their contents can be:
'O'(79) 'K'(75) '!'(33) '\0'(0)
?
?
..
Ç
Escape sequence with '\' and a number gives us the
character using that number as the ASCII code
- Examples:
#include <iostream>
using namespace std;
void main()
{
char s1[4]={'O','K','!','\0'};
char s2[4]={'O','K','!',0};
// Type conversion: 0 to '\0'
char s3[4]={'O','K','!'};
// Last value is auto-initialized to zero, i.e., s3[3] is zero.
char s4[4]="OK!";
// 'O', 'K', '!' are assigned as array elements, followed by 0 (ie. '\0').
char s5[ ]="OK!";
//
cout
cout
cout
cout
cout
cout
Auto: size=4
<< "OK!" << endl;
<< s1 << endl;
<< s2 << endl;
<< s3 << endl;
<< s4 << endl;
<< s5 << endl;
}
In each of these 6 cout statements:
- There is a sequence of 4 characters in
the memory and the starting address
is passed to << .
- << relies on the NULL character to
detect the ending of the string.
4 characters
6/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
™ We should always allocate 1 more space for the null character.
Eg. we write char s[4] to store a string with 3 characters like "O K !".
Programming mistake 1:
void main()
{
char s[3]="OK!";
cout << s << endl;
/ Compilation error: error C2117: 's' : array bounds overflow
Reason: The compiler expects 4 characters for "OK!\0".
}
Programming mistake 2:
void main()
{
char s[]={'O','K','!'};
cout << s << endl;
/ Treated as an array of 3 elements (3 characters).
Not including the NULL character to mark the end of string.
Ö
then "cout <<" can't determine the end of the string correctly.
}
'O'(79) 'K'(75) '!'(33)
Ö
-
?
?
..
Then some contents in the
memory after 'OK!' may be
displayed.
More examples:
(I) char s[20]="OKay";
(II) char s[]="Hi there.\n";
"Okay" initializes first
few characters.
Remaining ones are set
to 0.
(III)
Auto: size=11 (including '\0')
Here it shows the ASCII codes of
the space and endl characters.
char f_path[200];
cout << "Type the file pathname for input: ";
cin >> f_path;
Explanation:
- char f-path[200]; defines an array of 200 characters.
Since no intialization is given, all 200 elements are undefined at the
beginning (miscellaneous values / by-luck).
- At cin >> f-path;, 12 characters are entered into f-path[0..11].
An extra NULL character is ('\0', ie. 0) is added automatically at f-path[12].
(IV) To initialize a string to empty at declaration time, we can write: char s[10]="";
However, other than declaration time, we cannot assign to the whole cstring using =.
Question: Which one below can reset a non-empty string to empty?
(i) s="";
(ii) s[10]="";
(iii) s[0]='0';
(iv) s[0]=0;
char s[10]="abc";
s[10]="def"; // ERROR
s[]="def"; // ERROR
s="def"; // ERROR
(v) s[0]='\0';
7/16
Lecture Notes 5
-
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
The <cstring> standard library provides a number of functions for cstrings.
Eg. strlen(s) - returns the length of s (number of characters, not including '\0').
strcpy(s_destination, s_source) - copies the contents of a cstring to another (up to and including '\0').
strcmp(s1, s2) - compares s1 and s2's string contents up to '\0' (return 0 if they are the same).
stricmp(s1, s2) - similar to strcmp (but case-insensitive).
strchr(s1, c) - checks whether charater c is found in the string s.
strstr(s1, s_sub) - checks whether the string s1 contains a substring s_sub.
Interested students may refer to the <cstring> documentation.
Discussions
•
Significance of the null character '\0':
void my_cout(const char s[], int n)
{
int i=0;
while (_______________)
{
cout << s[i];
i++;
}
}
/* Output the cstring s char by char */
The above explains how '\0' in cstrings are actually applied in most operations.
•
Exercise: Display / Remove the last character in a cstring (ie. The character before '\0')
(i) void display_last(const char s[], int n)
{
}
(ii) void remove_last(const char s[], int n)
{
}
8/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
(LN 5-5) String Input
Reading a character
•
When we use >> to read a character, whitespaces (space, newline, tab) are skipped.
for (int i=0;i<10;i++)
{ char c;
cin >> c; // >> will jump across any whitespace (We won't get any whitespace in c).
cout << (int)c << " "; //display ascii code
}
abc abc abc abc Í input
97 98 99 97 98 99 97 98 99 97 Í output
Press any key to continue . . .
•
If we want to read characters including whitespaces, use cin.get():
for (int i=0;i<10;i++)
{ char c;
cin.get(c); // Will not skip whitespaces (Different from "cin>>c")
cout << (int)c << " "; //display ascii code
}
abc abc abc Í input
97 98 99 32 97 98 99 32 97 98 Í output
Press any key to continue . . .
Reading a string
Below are 2 methods to extract a string from cin.
Both of them add '\0' to the end of the obtained string.
•
When we use >> to read strings, each time only one word is obtained (delimited by whitespaces: '\n', tab, space).
void main()
{
char name[30];
cout << "Input your name: ";
cin >> name;
cout << "Hi, " << name << ".\n";
}
Input your name: Peter Pan
Hi, Peter.
Í not Peter Pan
Press any key to continue . . .
Extra input contents will be left in cin.
•
If we want to include whitespaces, use cin.getline() – read up to but not including <enter> (ie. '\n')
void main()
{
char name[30];
cout << "Input your name: ";
- Need to tell the max number of characters allowed in the array (including '\0')
- The contents up to '\n' (but not including '\n') will be stored in the array (name).
- The newline character ('\n") is removed from cin and discarded.
cin.getline(name,30);
cout << "Hi, " << name << ".\n";
}
Input your name: Peter Pan
Hi, Peter Pan.
Press any key to continue . . .
By default, it is delimited by '\n'. We may change it like cin.getline(name,30,'\t');
½ means to delimited by a tab.
9/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
cin.ignore() – discard extra inputs in cin
Suppose we apply "cin >>" and then "cin.getline(..)" like:
1
2
3
4
5
6
7
ID: 50123456
Name: Peter Pan
Welcome, Peter Pan (50123456).
Press any key to continue . . .
char name[30];
int id;
cout << "ID: ";
cin >> id;
cout << "Name: ";
cin.getline(name,30);
cout << "Welcome, " << name << " (" << id << ").\n";
However, the above fails: Line 6 will not wait for the user to type his name. Instead, line 7 will run immediately.
The fact:
After typing "50123456<enter>", the variable id will take the integer but the
<enter> character (ie. '\n') is left in cin.
The subsequent cin.getline() will then get '\n' and will not wait for input.
ID: 50123456
Name: Welcome, (50123456).
Press any key to continue . . .
Solution: use cin.ignore() that discards extra inputs left in cin:
char name[30];
int id;
cout << "ID: ";
cin >> id;
Î
cin.ignore();
cout << "Name: ";
cin.getline(name,30);
cout << "Welcome, " << name << " (" << id << ").\n";
(LN 5-6) String Input Predefined Character Functions
The following functions are available for handling characters:
‰
toupper(sym) – if sym is a lower case letter
‰
tolower(sym) – if sym is an upper case letter - return the corresponding lower case letter (ascii code)
- sym itself is not changed.
otherwise return sym itself (ascii code)
- return the corresponding upper case letter (ascii code)
- sym itself is not changed.
otherwise return sym itself (ascii code)
‰ isupper(sym) – returns true/fase based on whether sym contains an upper case letter
‰ islower(sym) – [similar]
‰ isspace(sym) – returns true/false based on whether sym contains a whitespace: blank, tab or newline
‰ isalpha(sym) – returns true/false based on whether sym contains a letter
‰ isdigit(sym) – returns true/false based on whether sym contains a digit
Application (see next page)
10/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
Application: Exaggerated Message
Input a string and output it in an exaggerated form:
(Turn all letters to upper case.
Use the minus character to underline all letters.)
That is great! Í input
*** THAT IS GREAT! ***
---- -- ----Press any key to continue . . .
Assume that the input string contains at most 29 characters.
#include <iostream>
using namespace std;
void main()
{
char s[30];
cin.getline(s,30); //input whole string in s[0,1,..]
// Output first line - turn all letters to upper case
cout << "*** ";
int i=0;
while (s[i]!='\0')
{
cout << char(toupper(s[i]));
i++;
}
cout << " ***\n";
Scan s[0,1,..] until '\0'.
Display the upper case letters
Note: If s[i] is not lower case
(eg. s[i] is '!', space, or
'A'..), toupper(s[i]) simply
return s[i] itself.
// Output second line: "underline" the letters
cout << "
";
i=0;
while (s[i]!='\0')
{
if (isalpha(s[i])) // 'a'-'z' or 'A'-'Z'
cout << "-";
else
cout << " ";
i++;
}
cout << "\n";
}
11/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
(LN 5-7) Exercise (Check your programs in PASS.)
void main()
{
..
LN5-Q1 Fraction Version D (Operators +, -, *, /, = =, <)
// ==,<,>
num1.display();
(i) Operator overloading:
if (num1 == num2)
• Remove the functions add, sub, mul and div.
•
cout << " == ";
if (num1 < num2)
Overload the operators +, -, *, / as friend functions to do the
same tasks. Example:
cout << " < ";
if (num1 > num2)
friend Fraction operator +(Fraction num1, Fraction num2);
cout << " > ";
num2.display();
cout << endl;
• In addition, overload the equality operator = =, the less than
operator < and the greater than operator > so that you can
compare two fractions directly.
Test the code with the driver program (available at the course web):
// addition
ans = num1 + num2;
...
}
Guideline for Fraction – Version D (i)
/* fraction.h */
//The Fraction Class
class Fraction {
public:
//Constructors
Fraction();
Fraction(int n, int d);
void display();
/* Friends: 4 ordinary (non-member) functions for Fraction
Calculations*/
friend Fraction add(Fraction num1, Fraction num2);
friend Fraction sub(Fraction num1, Fraction num2);
friend Fraction mul(Fraction num1, Fraction num2);
friend Fraction div(Fraction num1, Fraction num2);
private:
void reduce();
int numer, denom;
};
//Overloaded operators (as non-member functions) for Fraction
friend Fraction operator +(Fraction num1, Fraction num2);
friend Fraction operator -(Fraction num1, Fraction num2);
friend Fraction operator *(Fraction num1, Fraction num2);
friend Fraction operator /(Fraction num1, Fraction num2);
friend bool operator ==(Fraction num1, Fraction num2);
friend bool operator <(Fraction num1, Fraction num2);
friend bool operator >(Fraction num1, Fraction num2);
//Overloaded operator +
Fraction operator +(Fraction num1, Fraction num2)
{ int new_denom, new_numer;
new_numer=num1.numer*num2.denom+num2.numer*num1.denom;
new_denom=num1.denom*num2.denom;
return Fraction(new_numer,new_denom);
}
Same as the add
function in last version.
..// -, *, /
//Overloaded operator ==
bool operator ==(Fraction num1, Fraction num2)
{ Fraction diff=num1-num2;
return (diff.numer==0);
}
.. // <, >
12/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
(ii) const and &:
Define all the parameters of class type as call-by-reference parameters (&). Add the const modifiers to
the parameters and member functions wherever it is appropriate.
Guideline for Fraction – Version D (ii)
/* fraction.h */
class Fraction {
..
void display() const;
..
friend Fraction operator +(const Fraction &num1, const Fraction &num2);
!!! Handle -,*,/,>,<,== similar as + !!!
..
};
/* fraction.cpp */
..
void Fraction::display() const
{
}
..
..
Fraction operator +(const Fraction &num1, const Fraction &num2)
{
int new_denom, new_numer;
new_numer=num1.numer*num2.denom+num2.numer*num1.denom;
new_denom=num1.denom*num2.denom;
return Fraction(new_numer,new_denom);
}
..
!!! Handle -,*,/,>,<,== similar as + !!!
Submit Fraction.h and Fraction.cpp to PASS.
** NO NEED to upload the driver program (main function) to PASS.
13/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
LN5-Q2 Fraction Version E (Overloading << and >> operators)
Remove the member function display(). Then overload the insertion operator << and the extraction operator >> as
friend functions of class Fraction to perform the output and input tasks respectively.
The overloaded << should take an output stream and a Fraction as parameters and returns an output stream. The
overloaded >> should take an input stream and a Fraction as parameters and returns an input stream:
ostream &operator <<(ostream &outs, const Fraction &fract);
istream &operator >>(istream &ins, Fraction &fract);
Note
- At the beginning of Fraction.h, add:
#include <iostream>
using namespace std;
(
- In operator << above, the object outs may actually refer to the console output or an output file.
- In operator >> above, the object ins may actually refer to the console input (keyboadr) or an input file.
Sample run-down:
[Input Fraction 1 (a/b)]
From (f)ile or by (t)yping? Your choice [f/t]: f
Type the file pathname for input: c:\f1.txt
[Input Fraction 2 (a/b)]
From (f)ile or by (t)yping?
Type it: 2/3
1/2 <
1/2 +
1/2 1/2 *
1/2 /
Press
2/3
2/3
2/3
2/3
2/3
any
Your choice [f/t]: t
= 7/6
= -1/6
= 1/3
= 3/4
key to continue . . .
Test the code with the driver program (available at the course web). Submit Fraction.h and Fraction.cpp to PASS.
** NO NEED to upload the driver program (main function) to PASS.
Guideline for Fraction – Version E
/* fraction.h */
#include <iostream>
using namespace std;
class Fraction {
..
friend ostream &operator <<(ostream &outs, const Fraction &fract);
friend istream &operator >>(istream &ins, Fraction &fract);
..
};
/* fraction.cpp */
..
//Overloaded operator << for Fraction
ostream &operator <<(ostream &outs, const Fraction &fract)
{
outs << fract.numer << "/" << fract.denom;
.. //any special case – refer to the logic in void Fraction::display() const
return outs;
}
//Overloaded operator >> for Fraction
istream &operator >>(istream &ins, Fraction &fract)
{
char dummy;
ins >> fract.numer >> dummy >> fract.denom;
fract.reduce();
return ins;
}
..
&
WORTH
RE-DO all versions
AGAIN !!!
(without reading the guidelines)
14/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
LN5-Q3 UpPeRÙlOwEr
Sample 1
Complete the given program framework that inputs a string and
Type a string: Hi!
displays the transformed version with letter-cases altered.
hI! hOW ARE YOU?
How are you?
Press any key to continue . . .
Note:
- Each input string is at most 29 letters long.
Sample 2
- Hints are given in the program framework.
Type a string: WeLcOmE!
wElCoMe!
Press any key to continue . . .
LN5-Q4 Working with strings / Frequency Counts
Write a program that inputs a string (char
s[300];)
(1) whitespaces (' ', '\n', '\t')
Ï use isspace()
(2) digits ('0' – '9')
Ï use isdigit()
(3) each of 'a'-'z' (case-insensitive), whose count>0.
Ï use isalpha() and check ascii codes
(4) special characters
(excluded from the above (1), (2), or (3).)
Your program should involve the following
function that receives a null-terminated string (s)
and update caller's counters through other
parameters:
void countFequencies(
const char s[],
int &cntWhiteSpaces,
int &cntSpecial,
int &cntDigits,
int cntAlpha[] );
We don't return any value here. Because the
counters are of equivalent significance, we pass
all of them through call-by-reference parameters.
and counts the frequencies of:
Sample input/output (Underlined contents are input by user)
Input some text below (end with '@').
Welcome to 2009!
Be environmental friendly this year.
-- The earth@
Note
Frequencies
===========
Digits: 4
Whitespaces: 10
Special characters: 4
A: 3
B: 1
C: 1
D: 1
E: 9
F: 1
H: 3
I: 3
L: 3
M: 2
N: 4
O: 3
R: 4
S: 1
T: 5
V: 1
W: 1
Y: 2
Press any key to continue . . .
Note
Read the guidelines in the given code framework.
15/16
Lecture Notes 5
PROGRAMMING ENHANCEMENT COURSE | www.cs.cityu.edu.hk/~helena
LN5-Q5 Working with strings / Traversals and copying
Write a program that inputs a string and
Sample input/output
carries out the following operations:
(Underlined contents are input by user)
(i) copy non vowels (ie. not 'a', 'e', 'i', 'o', 'u',
'A', 'E', 'I', 'O', 'U')
Type a string: Mary said, "Programming is Fun!"
(ii) extract last word (alphabetical characters
only)
Last word is: Fun
(iii) search a sub-string (could be letters
and/or other characters like '!')
The copy without vowels is: Mry sd, "Prgrmmng s Fn!"
Type the sub-string: said
"said" is found at position 6
Press any key to continue . . .
The code framework is available for download.
LN5-Q6 Word with Highest Frequency (Optional / difficult)
Write a program that inputs a string and find the word that has the highest frequency in the string.
Ï (whole-word, not partial-string like "ing")
Sample input/output:
Assume
Type a string: Coding is fun and Coding is exciting so I like Coding
The word "Coding" has the highest frequency. It occurs 3 times.
Press any key to continue . . .
- The string contains words and spaces only (no punctuations).
- There is exactly one word that has the highest frequency.
16/16