C++ Programming
C++ Programming
Hour 2 Statements
If Statement
If-else Statement
Switch Statement
For Loop
While Loop
Do-While Loop
Break Statement
Continue Statement
Boolean-Expression
Conditional Operator
Hands-On Project: The Sum
Hour 4 String
A String Variable
Input String Data
Input String Sentence
Test Whether Inputted
String Length
Find a Character
Connect Strings
Exchange Strings
Find a Word’s Position
Insert a Substring
Hands-On Project: Show Inputted
Many free downloaded C++ compilers and editors are available on the internet;
you can choose one of them to write, edit, compile and execute your C++ codes.
Dev-C++ is an excellent C++ Compiler & Editor
Maybe you want to install free “Dev-C++” to your local computer, please
download it from the following website.
http://www.bloodshed.net/dev/devcpp.html.
If you don’t want “Dev-C++”, please download and install “Visual Studio”.
Or
Download Visual Studio
Visual Studio provides free tools to develop applications for a specific platform,
such as Visual C++, Visual C#, Visual Basic, Asp.net and Windows
applications.
Visual C++ contains all C++ libraries, C++ tools building and running C++
programs. Visual C++ is an IDE that can create a C++ development
environment.
To download a free edition of Visual Studio, go to
https://www.visualstudio.com
Install Visual Studio
In Visual Studio, Visual C++ is not installed by default. When installing, be sure
to choose Custom installation and then choose the Visual C++ components you
require.
Or
Online C++ Compiler & Editor
An online C++ compiler & editor are available at:
http://www.tutorialspoint.com/codingground.htm
When running the online C++ compiler & editor, you can type C++ codes into
the editor, click “Compile”, then click “Execute”, the result will appear.
What is C + +?
C++ is a general-purpose programming language, which is an extension of the C
language. C++ is an object-oriented programming language that is used
extensively.
Example 1.1
#include <iostream> using namespace std; int main() {
cout << "Hello World!" << endl; return 0;
} (Output: Hello World!)
Explanation:
“#include <iostream>” means including an input/output library named iostream
that helps input or output operation.
“using namespace std” means that “std” is a standard namespace , which can
solve the name conflict problems.
“int” is a return type, it specifies the return type of a function.
“main( )” is an obligatory function that runs main code of C++.
“cout <<” displays or show the contents.
“return 0” indicates the program run successfully.
C++ Comments
//
/* …… */
C++ comments are used to explain the current code, describe what this code is
doing. C++ compiler will ignore comments.
// is used in the single line comment.
/*…*/ is used in the multi line comments
Example 1.3
cout << “Hello World” ; // show “Hello World”
/* cout << is a C++ output command, meaning display or print.
*/
Explanation:
// show “Hello World” is a single line comment.
/* cout << is a C++ output command, meaning display or print. */ is a multi
line comment.
Note: Each C++ command ends with semicolon”;”.
Run First Programming
Hello World!
Write C++ codes to your favorite editor.
}
Explanation:
mychar is a name of variable, its value is “m”.
myinteger is a name of variable, its value is 168168.
mybool is a name of variable, its value is true.
“main ( ) { }” declares a main method.
Arithmetical Operators
Operators Running
- subtract
* multiply
/ divide
% get modulus
++ increase 1
-- decrease 1
% modulus operator divides the first number by the second number and returns
the remainder. e.g. 9%2=1.
Example 1.9
#include <iostream>
using namespace std;
int main( ) {
int a = 200, b = 100;
int sum = a + b; cout<< sum<<endl;
int divi = a / b; cout<< divi<<endl;
int modu = a % b; cout<< modu<<endl; // get remainder
cout << ++a << endl; // increase 1
return 0;
}
Output:
300
2
0
201
Explanation:
“int sum = a + b” means 100 plus 200.
“int divi = a / b” means 200 divide 100.
“int modu = a % b” means 200 modulus 100.
“++a” increases its value by 1.
Logical Operators
Operators Equivalent
&& and
|| or
! not
After using logical operators, the result will be true or false.
“1” represents true, “0” represents false.
Example 1.10
bool x=true; bool y=false; bool a= x && y; cout << a << endl; // output: 0
bool b=x || y; cout << b << endl; // output: 1
bool c=! x; cout << c << endl; // output: 0
Explanation:
“1” represents true, “0” represents false.
true && true && false
true; returns false; returns &&false;
true; false; returns false;
true II true; true II false; false II false;
returns true; returns true; return false;
! false; ! true; returns
returns true; false;
Assignment Operators
Operator Example Explanation
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
Example 1.11
#include <iostream>
using namespace std;
int main( ) {
int x=200; int y=100;
cout <<"200+=100 equals " << (x+=y)<< endl;
cout <<"300-=100 equals " << (x-=y)<< endl;
cout <<"200*=100 equals " << (x*=y)<< endl;
cout <<"20000%=100 equals "<< (x%=y)<< endl;
return 0;
}
Explanation:
x+=y; // x=x+y, x=200+100, output 300.
x-=y; // x=x-y, x=300-100, output 200.
x*=y; // x=x*y, x=200*100, output 20000.
x%y; // x=%y, x=2000000%100, output 0.
Comparison Operators
Operators Running
> greater than
< less than
>= greater than or equal
<= less than or equal
== equal
!= not equal
After using comparison operators, the result will be true or false.
Example 1.12
#include <iostream> using namespace std; int main( ) {
int x=200; int y=100; bool result1 = (x>y); cout << result1<< endl; bool result2
= (x<=y); cout << result2<< endl; bool result3 = (x!=y ); cout << result3 <<
endl; return 0;
};
Output:
1
0
1
Explanation:
“1” represents true.
“0” represents false.
#include <iostream>
using namespace std; int main(){
int a=10, b=20, c=30; // define three variables int sum; // define a variable
sum = a + b * c; // calculation cout << "a+b*c = "<< sum << endl; //
output return 0; // run successfully }
Save, and run the program.
Output:
a+b*c = 610
Explanation:
“#include <iostream>” includes an input/output library named iostream that
helps input or output operation.
“using namespace std” means that “std” is a standard namespace, which can
solve the name conflict problems.
“int” is a return type, it specifies the return type of a function.
“main( )” is an obligatory function that runs main code of C++.
“int a=10, b=20, c=30;” initialize three variables a, b, c.
“sum = a + b * c;” is an expression that assigns the result value to “sum”.
“cout <<” displays or show the contents.
“return 0” indicates the program run successfully.
Hour 2
Statements
If Statement
if ( test-expression ) { // if true do this; }
“if statement” executes codes inside { … } only if a specified condition is true,
does not execute any codes inside {…} if the condition is false.
Example 2.1
#include <iostream> using namespace std; int main( ) {
int a=200;
int b=100;
if (a>b){ // if true do this;
cout << "a is greater than b."; }
return 0;
} (Output: a is greater than b.)
Explanation:
( a>b ) is a test expression, namely (200>100), if returns true, it will execute the
codes inside the { }, if returns false, it will not execute the codes inside the { }.
If-else Statement
if ( test-expression) { // if true do this; }
else { // if false do this; }
“if...else statement” runs some code if a condition is true and another code if the
condition is false
Example 2.2
#include <iostream> using namespace std; int main( ) {
int a=100; int b=200; if (a>b) { // if true do this;
cout << "a is greater than b."; }
else { // if false do this;
cout << "a is less than b"; }
return 0;
} (Output: a is less than b.)
Explanation:
( a>b ) is a test expression, namely (100>200), if returns true, it will output ”a is
greater than b.” if returns false, it will output “a is less than b”.
Switch Statement
The value of the variable will compare each case first, if equals one of the “case”
value; it will execute that “case” code. “break;” terminates the code running.
Example 2.3
#include <iostream>
using namespace std; int main( ) {
int number=20; switch ( number ) { // “number” compares each case case 10 :
cout << "Running case 10 \n" ; break; case 20 : cout << "Running case 20 \n" ;
break; case 30 : cout << "Running case 30 \n" ; break; default : cout <<
"Running default code \n" ; break; }
return 0;
}
Output:
Running case 20
Explanation:
The number value is 20; it will match case 20, so it will run the code in case 20.
For Loop
for( init, test-expression, increment) { // some code; }
“for loop” runs a block of code by the specified number of times.
Example 2.4
#include <iostream> using namespace std; int main( ) {
int x;
for (x = 0; x <= 5; x++){ // repeat 5 times cout << x; }
return 0;
} (Output: 012345 )
Explanation:
x = 0 is an initializer,
x <= 5 is a test-expression, the code will run at most 5 times.
x++ means that x will increase 1each loop.
After 5 times loop, the code will output 012345.
While Loop
while ( test-expression ) { // some C++ code in here;
}
“while loop” loops through a block of code if the specified condition is true.
Example 2.5
#include <iostream> using namespace std; int main( ) {
int counter=0; while (counter < 8){ // run 8 times cout << "&"; counter++;
return 0;
} ( Output: &&&&&&&& )
Explanation:
“counter< 8” is a test expression, if the condition is true, the code will loop less
than 8 times, until the counter is 8, then the condition is false, the code will stop
running.
Do-While Loop
do{ // some c++ code in here } while ( test-
expression);
“do...while” loops through a block of code once, and then repeats the loop if the
specified condition is true.
Example 2.6
#include <iostream> using namespace std; int main( ) {
int counter=0; do {
cout << "@"; counter++;
} while (counter<8); // run 8 times return 0;
} ( Output: @@@@@@@@ )
Explanation:
“counter< 8” is a test expression, if the condition is true, the code will loop less
than 8 times, until the counter is 8, then the condition is false, the code will stop
running.
Break Statement
Break;
“break” keyword is used to stop the running of a loop according to the condition.
Example 2.7
#include <iostream> using namespace std; int main( ) {
int num=0;
while ( num<10 ){
if ( num==5 ) break; // leave the current while loop num++;
function1 ( );
type function1 ( ) { function2( ); }; type function2 (
) { };
Data that cannot change while running of the program is called constants.
}
Output:
$800 dollars.
Explanation:
#define SYMBOL “$” defines a constant named “SYMBOL”, its value is “$”.
The PRICE value is “80”, the MONEY value “dollars”.
Data Type Conversion
}
Output:
Number 1: 28
Number 2: 0
Explanation:
(int) can change the data type to integer.
(float) can change the data type to float pointing number.
(string) can change the data type to string.
And so on…..
Hands-On Project: Max Value
Array Operation Program
Write C++ codes to your favorite editor.
#include <iostream>
using namespace std; int main(){
int arr[5]= {20, -6, 0, 100, 78}; // create an array int max = arr[0]; // assume
the first element is the max for(int n=1; n<5; n++) // run 5 times
if(arr[n]>max) // compare the max with the current element max=arr[n]; //
the new max replaces the old max cout << "Max Value = "<< max << endl;
return 0;
mystring.empty( );
“mystring.empty( );” can test whether a user has inputted a word or sentence
before submitting data. If mystring is empty, it returns true. Otherwise, it returns
false.
Example 4.4
#include <string>
#include <iostream> using namespace std; int main( ) {
string mystring; if ( mystring.empty( )) {
cout << "Please enter your name: "; getline ( cin , mystring); // input Smith
John cout << mystring << endl; }
else {
cout << "You have entered your name, thank you! "; }
return 0;
}
Output:
Please enter your name:
Smith John
Explanation:
“if ( mystring.empty( ))” can check the user whether has entered data or not. If
true, it indicates the user has not entered any data.
String Length
mystring.size( );
“mystring.size( )” can check the length of a string, returns the total number of
characters and space in this string.
Example 4.5
#include<string> #include <iostream> using namespace std; int main( ) {
string mystring = "operating system"; int stringSize = mystring.size( ); // get
the size of string cout << "String length is: " << stringSize << endl; return 0;
}; ( Output: String length is: 16 )
Explanation:
“mystring.size( )” returns the size of “operating system”, the result is 16.
“return 0” indicates the program run correctly.
Note that a single space equals the string size of 1 character.
Find a Character
mystring. at(index);
“mystring.at (index)” gets a character from a string by index. The index of a
string begins with 0.
Example 4.6
#include<string> #include <iostream> using namespace std; int main( ) {
string mystring = "operating system"; char aCharacter = mystring.at(2); // get
one character cout << "The character is: " << aCharacter << endl; return 0;
}; ( Output: The character is: e )
Explanation:
“mystring.at(2)” gets a character at index 2 from the string “operating system”.
Note that the index of a string begins with 0.
Connect Strings
originalString.append ( newString ); originalString +
newString;
string1.swap(string2);
“swap( )” can exchange two strings’ values.
Example 4.8
#include<string>
#include <iostream>
using namespace std;
int main( ) {
string s1 = "Number One.";
string s2 = "Number Two.";
cout << "string1: " << s1<< endl;
cout << "string2: " << s2 << endl;
s1.swap(s2); // exchange two string values
cout << "string1: " << s1<< endl;
cout << "string2: " << s2 << endl;
return 0;
};
Output:
string1: Number One.
string2: Number Two.
string1: Number Two.
string2: Number One.
Explanation:
“s1.swap(s2);” swaps two string’s value.
Find a Word’s Position
mystring.find ( substring, start )
“find( )” can locate a substring’s place.
“Substring” means a substring that needs to search.
“start” means a start index to find a substring.
Example 4.9
#include<string>
#include <iostream>
using namespace std;
int main( ) {
string mystring = "An operating system.";
string substring = "system";
int position = mystring.find ( substring, 0 ); // get index
cout << "The position of substring is at: " << position << endl;
return 0;
}; (Output: The position of substring is at: 13 )
Explanation:
“system” locates index 13 in string “An operating System”. Note that string
index begins with 0. One space in string equals one character size.
Insert a Substring
originalString = insert ( index, substring );
“originalString = insert ( index, substring );” can insert a substring into an
original string.
“index” means a position where inserting a substring.
Example 4.10
#include<string> #include <iostream> using namespace std; int main( ) {
string originalString = "Flower is beautiful!"; string substring = "very ";
originalString.insert ( 10, substring); // insert a string cout << originalString
<< endl; return 0;
}; ( Output: Flower is very beautiful! )
Explanation:
“originalString.insert ( 10, substring);” inserts a substring “very” into an original
string “Flower is beautiful” at the index 10.
Hands-On Project: Show Inputted
String Operation Program
Write C++ codes to your favorite editor.
int main( ) {
Color Tint; // create an object named "Tint".
Tint.c1= "Red "; Tint.c2="Yellow "; cout << Tint.c1 << endl; cout << Tint.c2
<< endl; Tint.brightness ( ); return 0;
}
Output:
Red
Yellow
Green
Explanation:
“class Color” defines a class “Color”.
“Color Tint;” creates an object “Tint”.
“Tint.c1” means an object “Tint” references a variable “c1”.
“Tint.brightness ( );” means an object “Tint” calls a method “brightness( ).”
Constructor
Constructor is used to initialize variables. Constructor name is the same as class
name.
class ClassName{
int main( ) {
Color Tint; // create an object named "Tint".
cout << Tint.c1 << endl; cout << Tint.c2 << endl; Tint.brightness ( ); return 0;
}
Output:
Red
Yellow
Green
Explanation:
“Color ( ) { c1=”yellow”; c2=”purple”; }” is a constructor. It initializes
variable c1 as “yellow” and c2 as “purple”.
Destructors
A destructor is used to release the memory occupation, clean up the constructor
data.
~ destructor( );
Destructor name is the same as class name, but it is preceded by a ~ symbol.
Destructor has no any arguments, and has no return value.
Example 5.5
class Color { // define a class public:
string c1, c2; Color ( ) { c1=”yellow”; c2=”purple”; } ; // constructor ~ Color (
); // This is a destructor.
};
Explanation:
“~ Color ( );” is a destructor.
The declaration of destructor must follow the constructor.
Inheritance
A class can be inherited by its derived class. The object in derived class can be
treated as the object in base class.
The derived class inherits base class as following:
};
};
Explanation:
“Laptop” is a derived class, “Computer” is a base class.
“Laptop” class inherits “Computer” class.
Derived class inherits public member in base class.
Using Derived class
An object of a derived class can access the public member of a base class.
Example 5.7
#include<string>
#include <iostream> using namespace std; class Computer { // base class
public:
void display( ){
cout << "Computer OK!" << endl; }
};
};
int main ( ){
Laptop Lt; // derived class creates an object Lt Lt. display( ); // Lt calls base
class’s method return 0;
}
Output:
Computer OK!
Explanation:
“Lt. display( );” means a derived class’s object “Lt” calls base class’s method
display( ).
Public Permission
};
int main( ){
Computer obj; // create an object obj.display( ); // object references method
return 0;
}
Output:
Computer OK!
Explanation:
“obj.display( );” indicates an object “obj” calls “display( ){ }”.
Note that “obj” is outside the class “Computer”, but “obj” can access the public
member “display( ){ }”.
Private Permission
“private” is one of the “Member Access Specifier”,.
private class member can be accessed by the object in
the current class, but not in a derived class, not in
another class
Example 5.9
#include<string>
#include <iostream> using namespace std; class Computer {
private: // define private permission
void display( ){
cout << "Computer OK!" << endl; }} ;
int main( ){
Computer obj; // create an object obj.display( ); // error! References a
private method return 0;
} ( Output: Error Messages )
Explanation:
“ obj.display( );” indicates an object “obj” calls “display( ){ }”.
Note that “obj” is outside the class “Computer”, so “obj” cannot access the
private member “display( ){ }”.
Private Example
Example:
#include <string> #include <iostream> using namespace std; class Flower {
private: // define private permission string color = "The flower is red"; //
“color” is a private member public: void show(){
cout<< color; // access the private member }}; int main( ){
Flower obj; // create an object obj.show(); // ok! References a public method
return 0; }
Output:
The flower is red
Explanation:
Private variables can be accessed by the codes only in the same class.
Protected Permission
“protected” is one of the “Member Access Specifier”,.
protected class member can be accessed by the object
in the current class and derived class, but not in
another class.
Example 5.10
#include <iostream> using namespace std; class A {
protected: // define protected permission int prot; // declare a protected
member };
};
int main(){
B obj;
obj.myfunction(); return 0;
}
Output:
100
Explanation:
“protected: int prot;” declares a protected member.
“prot = 100;” access protected member of the base class, because the protected
member in base class can be accessed by derived class.
Class Method
int main( ){
Time obj; // create an object obj.setHour(10); return 0;
}
Output:
10
Explanation:
“void Time::setHour(int h){ }” defines a method outside the class. It means
“setHour( ){ }” belongs to the class “Time”.
“int hour = h;” means a variable “h” access a private member “hour” in the same
class. It’s valid!
Hands-On Project: My House
Class & Object
Write C++ codes to your favorite editor.
};
int main( ) {
House myHouse; // create an object “myHourse”
myHouse.height = 100; // object references variable myHouse.width = 200;
// object references variable myHouse.color = "white"; // object references
variable myHouse.size = "big"; // object references variable cout << "Height:
"<< myHouse.height <<endl; cout << "Width: "<< myHouse.width <<endl; cout
<< "Color: "<< myHouse.color <<endl; cout << "Size: "<< myHouse.size
<<endl; return 0;
dataType *PointerName;
pointerName = &variable;
}
Output:
Address of num is: 0x22ff58
Value of num is: 10
Explanation:
“numPointer” represents the address of “num”.
“*numPointer” represents the variable of “num”.
Pointer Initialize
}
Output:
Address of digit is: 0x22ff58
Value of digit is: 20
Explanation:
“int *digitPointer = &digit;” declares and initializes a pointer. “digitPointer”,
stores the memory address of “digit”
“digitPointer” represents the address of “digit”.
“*digitPointer” represents the variable of “digit”.
Using Pointer
}
Output:
20 10
20 10
Explanation:
“*pointer” represents a variable when running program.
“int pt1 = &x” means that pt1 is “x” variable.
“int pt2 = &y” means that pt2 is “y” variable.
“pt2 = pt1;” namely “y=x”.
“*pt1= 20;” namely “x=20”.
Exchange Pointers
}
Output:
100 200
200 100
Explanation:
“*pt” represents a variable when running program.
Before exchanging pts, *pt1 represents x, *pt2 represents y.
After exchanging pts, *pt1 represents y, *pt2 represents x.
Pointer and Array
*pointer = array;
“*pointer = array;” means that the pointer points to the first element of the array
Example 6.5
#include <string> #include <iostream> using namespace std; int main( ) {
int myarray[ 3 ] = { 10, 20, 30 }; int *pt = myarray; // pointer points to the first
element myarray[0]
cout << "The first value is: " << *pt << endl; pt++; // move pointer to next
element myarray[1]
cout << "The second value is: " << *pt << endl; pt++; // move pointer to next
element myarray[2]
cout << "The third value is: " << *pt << endl; return 0;
}
Output:
The first value is: 10
The second value is: 20
The third value is: 30
Explanation:
“int *pt = myarray;” means that the pointer points to the first element of
“myarray”. Namely myarrray[0].
“pt++” moves the pointer to next element.
“*pt” represents the array element.
Pointer Array
int a, b, c;
int *pointer[n] = { &a, &b, &c };
“int *pointer[n] = { &a, &b, &c };” declares a pointer array.
Example 6.6
#include <string> #include <iostream> using namespace std; int main( ) {
int a, b, c;
a = 10, b = 20, c = 30; int *myarray[3] = { &a, &b, &c }; // declare a pointer
array cout << myarray[0] + myarray[1] << endl; // a + b cout << myarray[2]
- myarray[1] << endl; // c - b return 0;
}
Output:
30
10
Explanation:
“int *myarray[3] = { &a, &b, &c };” declares a pointer array.
*myarray[0] represents “a” variable.
*myarray[1] represents “b” variable.
*myarray[2] represents “c” variable.
Pointer & String
}
Output:
8
Explanation:
“char *pt = “mystring”;” make the pointer points to the first character of
“mystring”.
*pt!=0 means that the pointer does not point to nothing.
“pt++” moves the pointer points to the next character in “mystring”.
Reference a Variable
}
Output:
100
200
Explanation:
“int &r = num” defines that the alia of “num” is “r”.
“r = 100;” indicates “num = 100”.
“num = 200;” indicates “r = 200”.
Reference an Object
int main( ) {
Color Tint; // create an object "Tint"
Color &r = Tint; //"r" is an alias of "Tint"
r.display( ); // namely Tint.dispaly(); return 0;
}
Output:
The color is blue.
Explanation:
“Color &r = Tint;” references an object “Tint”, whose alias is “r”.
“r.display( );” means that a referenced object can call a method “display( ){ }”.
Reference Arguments
int main( ) {
int x = 10, y = 20; cout << x << " " << y << endl; swap ( x, y ); cout << x << " "
<< y << endl; return 0;
}
Output:
10 20
20 10
Explanation:
“void swap ( int &a, int &b)” uses the reference in the argument.
Before swap, “a” is an alias of “x”, “b” is an alias of “y”.
After swap, “a” is an alias of “y”, “b” is an alias of “x”.
Hands-On Project: Address
Pointer Sample Program
Write C++ codes to your favorite editor.
}
Save, and run the program.
Output:
X value: 100
X address: 0x22ff54
Y value: 200
Y address: 0x22ff50
Explanation:
“int *xPointer = &x;” declares and initializes a pointer.
“xPointer” represents the address of “x”.
“*xPointer” represents the variable of “x”.
“int *yPointer;” declares a pointer.
“yPointer=&y;” stores address of “y” to pointer.
“cout<<"X value: "<<*xPointer<<endl;” shows the value of “*xPointer”.
“cout<<"X address: "<<xPointer<<endl;” shows the address of “xPointer”.
Hour 7
File Operation
Output One Character
cout.put (char C)
“cout.put (char C)” outputs one character.
Example 7.1
#include <string> #include <iostream> using namespace std; int main( ) {
char ch = 'C'; // Note: use single quote.
cout.put (ch) << endl; // output one character return 0;
( Output: C )
Explanation:
“#include <iostream>” includes iostream class that helps to input or output.
“cout.put ( ch )” display one character “C”.
Output String
cout.write (stringArray, stringLength);
“cout.write( )” can output a string.
“stringArray” defines the string as an array.
“stringLength” defines the string size.
Example 7.2
#include <iostream> #include <string.h> using namespace std; int main(){
char ch[ ]="This is a test"; // define a string array cout.write(ch, strlen(ch))
<<endl; // output a string return 0;
} ( Output: This is a test )
Explanation:
“ch[ ] = “This is a test” defines a string array.
“strlen ( ch )” gets the size of “ch” as the output length.
cout.write ( ) is used to output a string.
Input One Character
cin.get (char c );
}
Output:
C++ is a very good language.
Explanation:
“ifstream” class is used to read data from a file.
“ifstream fileObject ( “myFile.txt” );” creates an input file object “fileObject”.
“getline ( fileObject, mystring);” reads the file to mystring.
End of File
fileObject.eof ( );
“fileObject.eof( );” means that while reading data, eof( ) returns true at the end
of file, otherwise eof( ) returns false at somewhere on file.
Example 7.9
// “myFile.txt” has content: “C++ is a very good language.”
#include <iostream>
#include <fstream> #include <string> using namespace std; int main(){
char ch;
ifstream fileObject ( "myFile.txt"); while ( ! fileObject.eof( ) ) { // not at the end
of file fileObject.get (ch); // read characters from “myfile.txt”
cout << ch; // show all characters }
fileObject.close ( ); return 0;
}
Output:
C++ is a very good language.
Explanation:
“!fileObject.eof( )” indicates that “not at the end of file while reading data.”
“fileObject.get (ch);” keeps reading characters from “myfile.txt”
“fileObject.close( )” closes the file.
Hands-On Project: Process File
Read a File
}
Save, and run the program.
Output:
PHP in 8 Hours!
JAVA in 8 Hours!
JQUERY in 8 Hours!
JAVASCRIPT in 8 Hours!
Explanation:
Note that myFile.txt and the current C++ file should be in the same folder.
“ifstream fileObject("myFile.txt");” creates an input file object “fileObject”.
“if(!fileObject)” checks the existence of “myFile.txt”.
“return -1;” means the program runs unsuccessfully.
“if(!fileObject.eof())” checks the “end of the file”.
“fileObject.get(word)” reads characters from “myFile.txt”.
“cout<<word;” shows all characters in “myFile.txt”.
Hour 8
Static Exception Vector
this -> member
int main() {
Time t; // creates an object "t"
t.setHour(10); return 0;
}
Output:
The hour is: 10
Explanation:
“this” represents object “t”.
Static Variable
}
Output:
100
Explanation:
“static int num” means a static variable “num” can be referenced by a class or an
object.
“Account :: num” means a class “Account” can reference a static variable
“num”.
Non-static variable is referenced only by the object, not by class.
Static Function
int main() {
cout << Account :: myfunction( 200 ) << endl; /* a class references a method
directly */
return 0;
}
Output:
200
Explanation:
“static int myfunction(int n)” means a static function “myfunction(int n)” can be
referenced by a class or an object.
“Account :: myfunction ( 200)” means a class “Account” can references a static
function “myfunction( 200 )”.
Non-static function is referenced only by the object, not by class.
A++ or ++A
++A A plus 1 first, then run expression
A++ Run expression first, then A plus 1
--B B minus 1 first, then run expression
B-- Run expression first, then B minus 1.
Example 8.4
int A = 10, num; num = ++A - 2; /* A plus 1equals 11, 11 minus 2 equals 9, then
the result “9” assigns to num.*/
cout << num << endl; // ( output: 9 )
Example 8.5
int A = 10, num; num = A++ - 2; /* A minus 2 equals 8, the result “8” assigns to
num, then A plus 1.*/
cout << num << endl; // ( output: 8 )
Explanation:
“++A” increases 1 first, and then runs the expression.
“A++” runs the expression first, and then increases 1.
Call My Own Function
A function body includes its own function with the same function name, which
is known as a recursive function.
Example 8.6
#include <iostream> using namespace std; void myself(int n); int main() {
myself ( 1 ); return 0;
void myself ( int n){ // define a function cout << "Number " << n << endl;
++n;
if ( n == 4) return; // return means stop running else myself ( n ); // the
embedded function calls myself() }
Output:
Number 1
Number 2
Number 3
Explanation:
“void myself ( int n){ }” body contains an embedded function “myself(n);”
and “void myself ( int n)” is called by “myself(n);”, which is known as recursive
function.
“else myself ( n );” calls “void mysef (int n){… }” just like the loop statement,
until n equals 4, then leaves the loop statement.
Local & Global Variable
try
{ …}
catch(exception) {……}
“try {… …}” throws the exception out to the catch( ) { } block when an
exceptional error occurs.
“catch( ){ }” catches any exception from the try block, and handles it.
Example 8.9
#include <iostream>
#include <stdexcept>
using namespace std;
int main(){
string str1="JavaScript";
string str2="and";
try{ // exception may occur
str1.insert(100, str2); // “100” causes error
}
catch(logic_error){ // process the exception
cout << "Catch an exception." << endl;
cout << "Out of range!" << endl;
}
return 0;
}
Output:
Catch an exception.
Out of range!
Explanation:
In try{ } block, “str1.insert(100, str2);” causes an exception.
“catch(logic_error){ }” catches the exception.
Return Exception Message
try
{…}
return 0;
}
Output:
Catch an exception: basic_string:: at
Explanation:
“catch(exception& e)” can catch an exception. Note that its parameters are
“exception &e”, “e” is an exception object.
“e.what( )” returns exception message.
Throw Exception
try
{… throw…}
catch
{……}
“throw” can throw out an exception catch block that can handle the exception.
Example 8.11
#include <stdexcept> #include <iostream> using namespace std; int main (){
try{
int a=100, b=0; if(b==0){
throw b; // throw out an exception a=a/b;
catch (int e){ // handle the exception cout << "An exception occurred." <<
endl; cout << "The exception integer division by " << e ; }
return 0;
}
Output:
An exception occurred.
The exception integer division by 0
Explanation:
“throw b;” throws an exception from b. If b equals zero, a/b will be an error.
“catch (int e){ }” can catch and handle the exception.
Vector
Vectors are similar to arrays that can change in size. Just like arrays, vectors can
be any data type and its first index starts with zero.
If use vector in coding, C++ <vector> library must be included by #include
<vector> at the beginning of the program.
The syntax of creating a vector looks like this:
Vector <datatype> vector-name (size);
Example 8.12
vector <int> myVector (10); // Line 1
vector <double> prices (60); // Line2
vector <string> titles (18); // Line 3
Explanation:
Line 1: Declares a vector of 10 integer elements.
Line 2: Declares a vector of 60 double elements.
Line 3: Declares a vector of 18 string elements.
Vector.method( )
}
Output:
myVector size: 3
The third element: 30
Final element has been removed.
Explanation:
vector < int > myVector ( 1 ) creates a vector with 1 element.
myVector.push_back(20) adds an element with value 20 to the end of the vector.
myVector.push_back(30) adds an element with value 30 to the end of the vector.
myVector.size( ) gets the number of elements in myVector.
myVector.at(2) gets the value whose index is 2.
myVector.pop_back( ) removes the final element in myVector.
Vector.method( )
front( ) return the value of the first element
}
Output:
The first element: 0
The last element: 30
myVector is empty? 1
Explanation:
vector < int > myVector ( 1 ) creates a vector with 1 element.
myVector.push_back(20) adds an element with value 20 to the end of the vector.
myVector.push_back(30) adds an element with value 30 to the end of the vector.
myVector.front( ) returns the value of the first element.
myVector.back( ) returns the value of the last element.
myVector.clear( ) clears myVector.
myVector.empty( ) tests myVector to see if is empty.
“1” represents true, “0” represents false.
Hands-On Project: Error Occurs!
Exception Handling Program
Write C++ codes to your favorite editor.
cout<<"result="<<result<<endl; return 0; }
What is the output?
A. 100
B. 1000
C. 5000
D. 5050
cout<<"result="<<result<<endl; return 0; }
What is the output?
A. 100
B. 1000
C. 5000
D. 5050
catch (out_of_range){
cout<<"Exception: Out of range!"<<endl; }
return 0; }
What is the output?
A. 6
B. 8
C. Hello
D. Exception: Out of range!
A. Line 1
B. Line 2
C. Line 3
D. Line 4
90. getline( ) function reads from an input stream, its Syntax is ___?
A. getline(input, str);
B. getline(cin, str);
C. getline(enter, str);
D. getline(type, str);
cout<<n;
return 0; }
What is the output?
A. 3
B. 4
C. 5
D. 6
Dear My Friend, If you are not satisfied with this eBook, could you please
return the eBook for a refund within seven days of the date of purchase?
If you found any errors in this book, could you please send an email to me?
[email protected]
I will be very grateful for your email. Thank you very much!
Sincerely
Ray Yao