c++ notes
c++ notes
HISTORY OF C++
First program
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
EXAMPLE EXPAIN
Line 2: using namespace std means that we can use names for
objects and variables from the standard library.
Line 3: A blank line. C++ ignores white space. But we use it to
make the code more readable.
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
C++ Statements
A computer program is a list of "instructions" to be "executed"
by a computer.
If you forget the semicolon (;), an error will occur and the
program will not run:
C++ Output (Print Text)
The cout object, together with the << operator, is used to
output values/print text:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}
New Lines
To insert a new line, you can use the \n character:
EXAMPLE:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
You can also use another << operator and place the \
n character after the text, like this:
EXAMPLE:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << "\n";
cout << "I am learning C++";
return 0;
}
EXAMPLE:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << "\n\n";
cout << "I am learning C++";
return 0;
}
C++ Comments
Comments can be used to explain C++ code, and to make it more
readable. It can also be used to prevent execution when testing
alternative code. Comments can be singled-lined or multi-lined.
Single-line Comments :-
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by
the compiler (will not be executed).
This example uses a single-line comment before a line of
code:
// This is a comment
cout << "Hello World!";
C++ Variables
Variables are containers for storing data values.
Syntax
type variableName = value;
You can also declare a variable without assigning the value, and
assign the value later:
int myNum;
myNum = 15;
cout << myNum;
Other Types
A demonstration of other data types:
Display Variables
The cout object is used together with the << operator to display
variables.
int x = 5;
int y = 6;
int sum = x + y;
cout << sum;
int x = 5, y = 6, z = 50;
cout << x + y + z;
int x, y, z;
x = y = z = 50;
cout << x + y + z;
C++ Identifiers
All C++ variables must be identified with unique names.
// Good
int minutesPerHour = 60;
Constants
When you do not want others (or yourself) to change existing
variable values, use the const keyword (this will declare the
variable as "constant", which means unchangeable and read-
only):
const int myNum = 15; // myNum will always be 15
myNum = 10; // error: assignment of read-only variable
'myNum'
Notes On Constants
When you declare a constant variable, it must be assigned with a
value:
const int minutesPerHour = 60;
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7
float 4 bytes
Decimal digit
Numeric Types
Use int when you need to store a whole number without
decimals, like 35 or 1000, and float or double when you need a
floating point number (with decimals), like 9.99 or 3.14515.
int
float
double
Scientific Numbers
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;
Boolean Types
A boolean data type is declared with the bool keyword and can
only take the values true or false.
Character Types
The char data type is used to store a single character. The
character must be surrounded by single quotes, like 'A' or 'c':
Alternatively, if you are familiar with ASCII, you can use ASCII
values to display certain characters:
String Types
The string type is used to store a sequence of characters (text).
This is not a built-in type, but it behaves like one in its most basic
usage. String values must be surrounded by double quotes:
// Print variables
cout << "Number of items: " << items << "\n";
cout << "Cost per item: " << cost_per_item << "" << currency
<< "\n";
cout << "Total cost = " << total_cost << "" << currency << "\n";
Operators:-
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
1. Arithmetic Operators
Arithmetic operators are used to perform common mathematical
operations.
2. Assignment Operators
Assignment operators are used to assign values to variables.
int x = 10;
int x = 10;
x += 5;
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
3. Comparison Operators
Comparison operators are used to compare two values (or
variables). This is important in programming, because it helps us
to find answers and make decisions.
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
== Equal to x == y
!= Not equal x != y
&& Logical Returns true if both statements are true x < 5 && x < 10
and
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true
Strings
Strings are used for storing text/characters.
String Concatenation
The + operator can be used between strings to add them together
to make a new string. This is called concatenation:
Example:-
Append
A string in C++ is actually an object, which contain functions
that can perform certain operations on strings. For example, you
can also concatenate strings with the append() function:
//error
(string x = "10";
int y = 20;
string z = x + y;)
String Length
To get the length of a string, use the length() function:
Access Strings
You can access the characters in a string by referring to its index
number inside square brackets [].
This example prints the first character in myString:
String indexes start with 0: [0] is the first character. [1] is the
second character, etc.
myString.at(0) = 'J';
cout << myString; // Outputs Jello
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
Omitting Namespace
You might see some C++ programs that run without the standard
namespace library. The using namespace std line can be omitted
and replaced with the std keyword, followed by the :: operator
for string (and cout) objects:
Example:-
#include <iostream>
#include <string>
// using namespace std; - Remove this line
int main() {
std::string greeting = "Hello";
std::cout << greeting;
return 0;
}
C-Style Strings
C-style strings are created with the char type instead of string.
The name comes from the C language, which, unlike many other
programming languages, does not have a string type for easily
creating string variables. Instead, you must use the char type and
create an array of characters to make a "string" in C.
C++ Math
C++ has many functions that allows you to perform mathematical
tasks on numbers.
C++ Booleans
Very often, in programming, you will need a data type that can
only have one of two values, like:
YES / NO
ON / OFF
TRUE / FALSE
For this, C++ has a bool data type, which can take the
values true (1) or false (0).
Boolean Values
A boolean variable is declared with the bool keyword and can
take the values true or false:
Boolean Expression
A Boolean expression returns a boolean value, which is
either 1 (true) or 0 (false).
This is useful for building logic and finding answers.
You can use a comparison operator, such as the greater than (>)
operator, to find out if an expression (or variable) is true or false:
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true),because 10 is higher than 9
Or even easier:
cout << (10 > 9); // returns 1 (true), because 10 is higher than 9
int x = 10;
cout << (x == 10); // returns 1 (true), because the value of x is
equal to 10
The if Statement
Use the if statement to specify a block of C++ code to be
executed if a condition is true.
if (condition) {
// block of code to be executed if the condition is true
}
Syntax:-
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example:-
Syntax:-
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example:-
Syntax:-
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Example:-
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
This will stop the execution of more code and case testing inside
the block.
When a match is found, and the job is done, it's time for a break.
There is no need for more testing
Example:-
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday";
break;
case 7:
cout << "Today is Sunday";
break;
default:
cout << "Looking forward to the Weekend";
}
C++ Loops
Loops can execute a block of code as long as a specified
condition is reached.
Loops are handy because they save time, reduce errors, and they
make code more readable.
Syntax:-
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and
over again, as long as a variable (i) is less than 5:
Example:-
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
Syntax:-
do {
// code block to be executed
}
while (condition);
example below uses a do/while loop. The loop will always be
executed at least once, even if the condition is false, because the
code block is executed before the condition is tested:
Example:-
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
For Loop
When you know exactly how many times you want to loop
through a block of code, use the for loop instead of a while loop:
Syntax:-
Example:-
Example:-
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}
Nested Loops
It is also possible to place a loop inside another loop. This is
called a nested loop.
The "inner loop" will be executed one time for each iteration of
the "outer loop":
Example:-
// Outer loop
for (int i = 1; i <= 2; ++i) {
cout << "Outer: " << i << "\n"; // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; ++j) {
cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
}
}
C++ Break
You have already seen the break statement used in an earlier
chapter of this tutorial. It was used to "jump out" of
a switch statement.
Example:-
Continue
The continue statement breaks one iteration (in the loop), if a
specified condition occurs, and continues with the next iteration
in the loop.
Break Example:-
int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}
Continue example:-
int i = 0;
while (i < 10) {
if (i == 4) {
i++;
continue;
}
cout << i << "\n";
i++;
}
Arrays
Arrays are used to store multiple values in a single variable,
instead of declaring separate variables for each value.
string cars[4];
Example:-
cars[0] = "Opel";
Example:-
Example:-
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
cars[2] = "Ford";
cars[3] = "Mazda";
cars[4] = "Tesla";
Example:-fixed size(arrays)
Vectors
For operations that require adding and removing array elements,
C++ provides vectors, which are resizable arrays.
Vectors are found in the <vector> library, and they come with
many useful functions to add, remove and modify elements:
Example:-dynamic size(vectors)
// A vector with 3 elements
vector<string> cars = {"Volvo", "BMW", "Ford"};
Example:-
Why did the result show 20 instead of 5, when the array contains
5 elements?
You learned from the Data Types chapter that an int type is
usually 4 bytes, so from the example above, 4 x 5 (4 bytes x 5
elements) = 20 bytes.
Example:-
Instead of writing:
Example:-
Multi-Dimensional Arrays
A multidimensional array is essentially an array of arrays. This
means that each element of the array is another array, and it can
have more than two dimensions, depending on the requirement.
The most common example is a two-dimensional array, which
can be visualized as a table with rows and columns.
1. Declaration of a 2D Array:
int arr[3][4];
int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} };
3. Accessing Elements in a 2D Array:
5. 3D Array Example:
int arr[2][3][4];
you can initialize it
int arr[2][3][4] = {
{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}, {{13, 14, 15, 16},
{17, 18, 19, 20}, {21, 22, 23, 24}}
};
6. Accessing 3D Array Elements:
#include<iostream>
using namespace std;
int main() {
int arr[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};
Example:-
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
Structures
a structure (struct) is a user-defined data type that allows you to
combine different types of variables under a single name. This is
useful when you need to represent more complex data, like a
group of variables that logically belong together. Structures are
similar to classes, but by default, their members are public
(whereas class members are private by default).
Defining a Structure
struct StructureName {
// Data members
type1 member1;
type2 member2;
};
#include <iostream>
struct Person {
string name;
int age;
float height;
};
int main() {
Person p1;
p1.age = 25;
p1.height = 5.9;
return 0;
Example:-
struct {
int myNum;
string myString;
} myStructure;
myStructure.myNum = 1;
myStructure.myString = "Hello World!";
Example:-
struct {
int myNum;
string myString;
} myStruct1, myStruct2, myStruct3;
Named Structures
By giving a name to the structure, you can treat it as a data type.
This means that you can create variables with this structure
anywhere in the program at any time.
struct myDataType {
int myNum;
string myString;
};
To declare a variable that uses the structure, use the name of the
structure as the data type of the variable:
myDataType myVar;
Enumeration (Enums)
An enum is a special type that represents a group of
constants (unchangeable values).
To create an enum, use the enum keyword, followed by the name
of the enum, and separate the enum items with a comma:
enum Level {
LOW,
MEDIUM,
HIGH
};
Now that you have created an enum variable (myVar), you can
assign a value to it.
The assigned value must be one of the items inside the enum
(LOW, MEDIUM or HIGH):
By default, the first item (LOW) has the value 0, the second
(MEDIUM) has the value 1, etc.
#include <iostream>
return 0;
Change Values
As you know, the first item of an enum has the value 0. The
second has the value 1, and so on.
To make more sense of the values, you can easily change them:
enum Level {
LOW = 25,
MEDIUM = 50,
HIGH = 75
};
int main() {
enum Level myVar = MEDIUM;
cout << myVar; // Now outputs 50
return 0;
}
enum Level {
LOW = 1,
MEDIUM,
HIGH
};
int main() {
enum Level myVar = MEDIUM;
switch (myVar) {
case 1:
printf("Low Level");
break;
case 2:
printf("Medium level");
break;
case 3:
printf("High level");
break;
}
return 0;
}
Creating References
A reference variable is a "reference" to an existing variable, and
it is created with the & operator:
Now, we can use either the variable name food or the reference
name meal to refer to the food variable:
Example:-
Memory Address
In the example from the previous page, the & operator was used
to create a reference variable. But it can also be used to get the
memory address of a variable; which is the location of where the
variable is stored on the computer.
To access it, use the & operator, and the result will represent
where the variable is stored:
Example:-
Creating Pointers
You learned from the previous chapter, that we can get
the memory address of a variable by using the & operator:
Example:-
Example:-
string food = "Pizza";
string* ptr = &food;
cout << food << "\n";
Example Explain:-
Use the & operator to store the memory address of the variable
called food, and assign it to the pointer.
Example:-
Exampe:-
Functions
A function is a block of code which only runs when it is
called.
Create a Function
C++ provides some pre-defined functions, such
as main(), which is used to execute code. But you can
also create your own functions to perform certain
actions.
To create (often referred to as declare) a function, specify the
name of the function, followed by parentheses ():
Syntax:-
void myFunction() {
// code to be executed
}
Example Explained
Call a Function
Declared functions are not executed immediately. They are
"saved for later use", and will be executed later, when they are
called.
Example:-
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction();
return 0;
}
Syntax:-
Example:-
int main() {
myFunction("Doora");
myFunction("Doremon");
myFunction("lio");
return 0;
}
When a parameter is passed to the function, it is called an
argument. So, from the example above : fname is a parameter,
while Doora , Doremon and lio are arguments.
Example:-
int main() {
myFunction("America");
myFunction("Nepal");
myFunction();
myFunction("USA");
return 0;
}
Multiple Parameters
Inside the function, you can add as many parameters as you
want:
Example:-
int main() {
myFunction("Sachin",23);
myFunction("Kajal", 24);
myFunction("Riya", 22);
return 0;
}
Return Values
The void keyword, used in the previous examples, indicates that
the function should not return a value. If you want the function to
return a value, you can use a data type (such as int, string, etc.)
instead of void, and use the return keyword inside the function:
Example:-
int myFunction(int x) {
return 8 + x;
}
int main() {
cout << myFunction(9);
return 0;
}
int main() {
cout << myFunction(11,4);
return 0;
}
Pass By Reference
In the examples from the previous page, we used normal
variables when we passed parameters to a function. You can also
pass a reference to the function. This can be useful when you
need to change the value of the arguments:
Example:-
int main() {
int firstNum = 60;
int secondNum = 20;
swapNums(firstNum, secondNum);
return 0;
}
Example:-
int main() {
int myNumbers[5] = {50,60,30,40,20};
myFunction(myNumbers);
return 0;
}
Example Explained
Note that when you call the function, you only need to use the
name of the array when passing it as an
argument myFunction(myNumbers). However, the full
declaration of the array is needed in the function parameter (int
myNumbers[5]).
Real Example:-
Fahrenheit to Celsius
Function Overloading
With function overloading, multiple functions can have the
same name with different parameters:
Example :-
int main() {
int N1 = FunInt(5, 5);
double N2 = FunDouble(6.5, 8.5);
cout << "Int: " << N1 << "\n";
cout << "Double: " << N2;
return 0;
}
Variable Scope :-
variable scope refers to the region of the program where a
variable can be accessed or used. Understanding the scope of
variables is essential to avoid errors, such as using variables that
are not defined or are out of scope.
variables are only accessible inside the region they are created.
This is called scope.
Example:-
void myFunction() {
int x = 5;
cout << x;
int main() {
myFunction();
return 0;
}
Global variables are available from within any scope, global and
local.
Example:-
int x = 5;
void myFunction() {
cout << x << "\n";
}
int main() {
myFunction();
cout << x;
return 0;
}
Recursion
Recursion is the technique of making a function call itself. This
technique provides a way to break complicated problems down
into simple problems which are easier to solve.
#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n, result;
result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}
int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}
What is OOP ?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions
that perform operations on the data, while object-oriented
programming is about creating objects that contain both data and
functions.
Object-oriented programming has several advantages over
procedural programming:
Classes Objects
Apple
Fruit Mango
Create a Class
To create a class, use the class keyword:
Example:-
class MyClass { // The class
public:
int myNum;
string myString;
};
Create an Object
An object is created from a class. We have already created
the class named MyClass, so now we can use this to create
objects.
myObj.myNum = 15;
myObj.myString = "Some text";
Multiple Objects
class Car{
public:
string brand;
string model;
int year;
};
int main() {
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X3";
carObj1.year = 2024;
Car carObj2;
carObj2.brand = "Mahindra";
carObj2.model = "XUV700";
carObj2.year = 2024;
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
Class Methods
Methods are functions that belongs to the class.
Inside Example:-
class MyClass {
public:
void myMethod() { // Method/function
defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj;
myObj.myMethod();
return 0;
}
Outside Example:-
class MyClass {
public:
void myMethod();
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj;
myObj.myMethod();
return 0;
}
Constructors
A constructor in C++ is a special method that is automatically
called when an object of a class is created.
To create a constructor, use the same name as the class, followed
by parentheses ():
Example:-
class MyClass { //Class name
public:
MyClass() { //Function name //
Constructor
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
(this will call the constructor)
return 0;
}
Constructor Parameters
Constructors can also take parameters (just like regular
functions), which can be useful for setting initial values for
attributes.
The following class have brand, model and year attributes, and a
constructor with different parameters. Inside the constructor we
set the attributes equal to the constructor parameters (brand=x,
etc). When we call the constructor (by creating an object of the
class), we pass parameters to the constructor, which will set the
value of the corresponding attributes to the same:
Example:-
class Car {
public:
string brand;
string model;
int year;
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};
int main() {
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
Access Specifiers
By now, you are quite familiar with the public keyword that
appears in all of our class examples:
Example:-
class MyClass {
Example:-
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};
int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive"
data is hidden from users. To achieve this, you must declare class
variables/attributes as private (cannot be accessed from outside
the class). If you want others to read or modify the value of a
private member, you can provide public get and set methods.
Example:-
#include <iostream>
class Employee {
private:
int salary;
public:
void setSalary(int s) {
salary = s;
int getSalary() {
return salary;
};
int main() {
Employee myObj;
myObj.setSalary(50000);
return 0;
Example explained
Inheritance
In C++, it is possible to inherit attributes and methods from one
class to another. We group the "inheritance concept" into two
categories:
In the example below, the Car class (child) inherits the attributes
and methods from the Vehicle class (parent):
Example:-
#include <iostream>
public:
void eat() {
};
void bark() {
};
int main() {
Dog myDog;
myDog.eat();
myDog.bark();
return 0;
Types of Inheritance:-
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
1. Single Inheritance
Example:-
class Base {
};
};
2. Multiple Inheritance
Example:-
class Base1 {
};
class Base2 {
};
3. Multilevel Inheritance
Example:-
class Base {
};
};
};
4. Hierarchical Inheritance
Example:-
class Base {
};
class Derived1 : public Base {
};
};
5. Hybrid Inheritance
Example:-
class Base {
};
};
};
class Derived3 : public Derived1, public Derived2 {
};
Summary of Types:
Access Specifiers
we have only used public (members of a class are accessible from
outside the class) and private (members can only be accessed
within the class). The third specifier, protected, is similar
to private, but it can also be accessed in the inherited class:
Example:-
// Base class
class Employee {
protected: // Protected access specifier
int salary;
};
// Derived class
class Programmer: public Employee {
public:
int bonus;
void setSalary(int s) {
salary = s;
}
int getSalary() {
return salary;
}
};
int main() {
Programmer myObj;
myObj.setSalary(50000);
myObj.bonus = 15000;
cout << "Salary: " << myObj.getSalary() << "\n";
cout << "Bonus: " << myObj.bonus << "\n";
return 0;
}
Polymorphism
Polymorphism means "many forms", and it occurs when we have
many classes that are related to each other by inheritance.
Polymorphism uses those methods to perform different tasks.
This allows us to perform a single action in different ways.
Example:-
// Base class
class Animal {
public:
void animalSound() {
cout << "The animal makes a sound \n";
}
};
// Derived class
class Pig : public Animal {
public:
void animalSound() {
cout << "The pig says: wee wee \n";
}
};
// Derived class
class Dog : public Animal {
public:
void animalSound() {
cout << "The dog says: bow wow \n";
}
};
Files
The fstream library allows us to work with files.
To use the fstream library, include both the
standard <iostream> AND the <fstream> header file:
Example:-
#include <iostream>
#include <fstream>
There are three classes included in the fstream library, which are
used to create, write or read files:
Class Description
Example:-
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
// Write to the file
MyFile << "Files can be tricky, but it is fun enough!";