Professional Documents
Culture Documents
CPP Record Mid 2
CPP Record Mid 2
DESCRIPTION:
Syntax:
Default constructor
class sample{
public:
// Default constructor
sample() {
};
Parameterized constructor
class sample {
public:
// Parameterized constructor
};
There are two types of constructors,they are default constructor and parameterized
constructor. A default constructor in C++ is a constructor with no parameters that is
automatically called when you create an object of a class. It has the name name as the
class and it has no return type. Parameterized constructor is also same as default
constructor but it has parameters.
SOURCE CODE:
#include <iostream>
class sample {
public:
sample() {
sample(int value) {
this->value = value;
void display() {
private:
int value;
};
int main() {
sample obj1;
sample obj2(42);
obj2.display();
return 0;
SAVING: CONSTRUCTOR.CPP
EXECUTiING: CTRL+F9
OUTPUT:
DESCRIPTION:
Syntax:
class sample {
public:
// Parameterized constructor
};
SOURCE CODE:
#include<iostream.h>
class sample
int x;
public:
sample(int a)
x=a;
void display()
cout<<endl<<"value of x is "<<x<<endl;
};
int main()
cin>>abc;
sample s1(abc);
s1.display();
return 0;
SAVING: PARAMETERCONST.CPP
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
Syntax:
class sample{
public:
// Default constructor
sample() {
};
SOURCE CODE:
#include<iostream.h>
class sample
public:
sample()
};
int main()
sample s1;
return 0;
SAVING: DEFAULTCONST.CPP
OUTPUT:
DESCRIPTION:
#include<iostream.h>
#include<iostream.h>
SOURCE CODE:
#include <iostream>
class Sample {
public:
int value;
// Parameterized constructor
Sample(int val) {
value = val;
cout << "Parameterized constructor called with value: " << val << endl;
};
int main() {
Sample obj1(42);
SAVING: IMPLICITEXPLICIT.CPP
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
The below program is written using default constructor and parameterized constructor.
Syntax:
Default constructor
class sample{
public:
// Default constructor
sample() {
};
Parameterized constructor
class sample {
public:
// Parameterized constructor
};
SOURCE CODE:
#include <iostream>
class Sample {
public:
int value;
// Default constructor
value = 0;
Sample(int val) {
value = val;
cout << "Parameterized constructor called with value: " << val << endl;
cout << "Parameterized constructor called with values: " << val1 << " and " << val2
<< endl;
};
int main() {
return 0;
SAVING: CONSTRUCTORS.CPP
EXECUTING: CTRL+F9
Syntax:
class class_name
{
public:
class_name()
{ //constructor code }
class_name(variables)
{ //constructor code }
…other variables and functions
};
SOURCE CODE:
#include<iostream>
class MyClass {
private:
int value;
public:
// Default constructor
MyClass() {
value = 0;
MyClass(int val) {
value = val;
void display() {
};
int main()
obj1.display();
obj2.display();
obj3.display();
return 0;
EXECUTING: CTRL+F9
Syntax:
class class_name
{
public:
class_name()
{ //constructor code }
class_name(variables)
{ //constructor code }
…other variables and functions
friend class_name(variables);
};
SOURCE CODE:
#include <iostream>
class MyClass {
private:
int value;
public:
MyClass() {
value = 0;
MyClass(int val) {
value = val;
};
MyClass newObj;
return newObj;
int main()
MyClass obj1;
MyClass obj2(5);
obj1.display();
obj2.display();
obj3.display();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION: In C++, you can create constructors with default arguments, which allows
you to initialize objects of a class with a set of default values for the constructor
parameters. This is a useful feature to make your class more flexible and user-friendly.
Syntax:
class class_name
{
public:
class_name()
{ //constructor code }
class_name(..variables , variable_name=value)
{ //constructor code }
};
SOURCE CODE:
#include <iostream>
class MyClass {
private:
int value1;
int value2;
public:
value1 = val1;
value2 = val2;
void display() {
cout << "Value1: " << value1 << ", Value2: " << value2 << endl;
};
int main() {
obj1.display();
obj2.display();
obj3.display();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION: A class objects can be initialized dynamically. That is to say that the initial
values of an object may be provided during runtime. One advantage of dynamic
initialization is that we can provide various initialization formats using overloaded
constructors. This provides the flexiability of using different format of data at run time
depending upon the situation.
SOURCE CODE:
#include<iostream>
class FD
int years;
float rate;
float return_value;
public :
FD(){}
int display()
} };
pamount=p;
years=y;
return_value=pamount;
for(int i=1;i<=y;i++)
return_value=return_value*(1.0+r);
pamount=p;
years=y;
rate=r;
return_value=pamount;
for(int i=1;i<=y;i++)
return_value=return_value*(1.0+float(r)/100);
int main()
FD f1,f2,f3;
long int p;
int y,R;
float r;
cin>>p>>y>>R;
f1=FD(p,y,R);
cin>>p>>y>>r;
f2=FD(p,y,r);
cin>>p>>y;
f3=FD(p,y);
f1.display();
f2.display();
f3.display();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
Syntax:
class class_name
{
public:
class_name()
{ //constructor code }
class_name(class_name & obj)
{
//obj is same class another objects
//copy constructor code
}
// …other variables and functions
};
.SOURCE CODE:
#include<iostream>
class code
int id;
public:
code(){}
code(int a)
id=a;
id=x.id;
void display()
cout<<id;
};
int main()
code a(200);
code b(a);
code c=a;
code d;
d=a;
cout<<"\n id of a=";a.display();
cout<<"\n id of b=";b.display();
cout<<"\n id of c=";c.display();
cout<<"\n id of d=";d.display();
return 0;
EXECUTING: CTRL+F9
delete pointer_variable;
SOURCE CODE:
#include<iostream>
#include<string.h>
class strin
char *name;
int length;
public:
strin()
length=0;
name=new char[length+1];
strin(char *s)
length=strlen(s);
name=new char[length+1];
void display()
{ cout<<name<<"\n"; }
};
length=a.length+b.length;
delete name;
name=new char[length+1];
strcpy(name,a.name);
strcat(name,b.name);
int main()
s1.join(name1,name2);
s2.join(s1,name3);
name1.display();
name2.display();
name3.display();
s1.display();
s2.display();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
A destructor never takes any argument nor does it return any value .It will be invoked
implicitly by the complier upon exist from the program or block or function as the case
may be ,to clean up storage that is no longer accessible.
Syntax:
class class_name
public:
class_name() //constructor
~class_name() //destructor
};
SOURCE CODE:
#include<iostream>
int count=0;
class alpha
public:
alpha()
count++;
~alpha()
count--;
};
int main()
alpha a1,a2,a3,a4;
alpha a5;
alpha a6;
return 0;
EXECUTING: CTRL+F9
DESCRIPTION:
Syntax:
class ClassName {
public:
};
SOURCE CODE:
#include <iostream>
class Counter {
private:
int count;
public:
Counter() : count(0) {}
Counter(int c) : count(c) {}
void operator++() {
++count;
void operator--() {
--count;
void display() {
};
int main() {
Counter c1;
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
In this program, we have a Counter class that has an int member variable count. We define
a display method to print the current value of count. We use a friend function operator-
to overload the unary operator -. The friend function takes a Counter object as an
argument and returns a new Counter object with the negation of the count value.
In the main function, we create two instances of Counter, c1 and c2. We apply the unary
minus operator to c1 using the friend function, and then print the results using the display
method.
Syntax:
class ClassName {
private:
// class members
public:
};
SOURCE CODE:
#include <iostream>
class Counter {
private:
int count;
public:
Counter() : count(0) {}
Counter(int c) : count(c) {}
void display() {
};
Counter operator-(Counter& c) {
return Counter(-c.count);
int main() {
Counter c1(5);
Counter c2;
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
In this program, we define a Complex class that represents complex numbers with real
and imaginary parts. We overload the + operator for the Complex class to perform addition
of complex numbers. The display method is used to print the real and imaginary parts of
the complex number.
In the main function, we create three instances of the Complex class, c1, c2, and c3, and
perform the addition of two complex numbers using the overloaded + operator. The
program then prints the results to the console using the display method.
Syntax:
class ClassName {
// Class members
public:
// Usually involves operations between the current object and the passed
object
};
SOURCE CODE:
#include <iostream>
class Complex {
private:
float real;
float imag;
public:
Complex temp;
return temp;
void display() {
cout << "Real: " << real << " Imaginary: " << imag << endl;
};
int main() {
Complex c3;
c1.display();
c2.display();
c3.display();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
In this program, we define a Complex class that represents complex numbers with real
and imaginary parts. We use a friend function to overload the + operator for the Complex
class to perform addition of complex numbers. The display method is used to print the
real and imaginary parts of the complex number.
In the main function, we create three instances of the Complex class, c1, c2, and c3, and
perform the addition of two complex numbers using the overloaded + operator. The
program then prints the results to the console using the display method.
Syntax:
class ClassName {
private:
// class members
public:
};
SOURCE CODE:
#include <iostream>
class Complex {
private:
float real;
float imag;
public:
void display() {
cout << "Real: " << real << " Imaginary: " << imag << endl;
};
Complex temp;
return temp;
int main() {
Complex c3;
c1.display();
c2.display();
c3.display();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
In this program, we define a Complex class that represents complex numbers with real
and imaginary parts. We overload the << operator for output and the >> operator for input
using friend functions. The << operator is used to display the complex number, and the
>> operator is used to input the real and imaginary parts of the complex number.
In the main function, we create an instance of the Complex class, c1, and use the
overloaded << and >> operators to display and input the complex number respectively.
class ClassName {
// class members
public:
};
return out;
class ClassName {
// class members
public:
};
return in;
SOURCE CODE:
#include <iostream>
class Complex {
private:
float real;
float imag;
public:
};
out << "Real: " << c.real << " Imaginary: " << c.imag << endl;
return out;
in >> c.real;
in >> c.imag;
return in;
int main() {
Complex c1;
cout << "The complex number entered is: " << endl;
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
1. The operator overloading function must precede with friend keyword, and declare a
function class scope.
2. Friend operator function takes two parameters in a binary operator, varies one
parameter in a unary operator
3. C++ increases the versatility of operator overloading in C++ since functions can be
overloaded as friend functions as well,
4. Friend function can access private members of a class directly
//Statements;
SOURCE CODE:
#include<iostream>
#include<conio.h>
class vector{
int i,v[size];
public:
vector();
vector(int *x);
vector :: vector(){
for(i=0;i<size;i++) v[i]=0; }
for(i=0;i<size;i++) v[i]=x[i];}
int i;
for(i=0;i<size;i++)
c.v[i]=a*b.v[i];
return c;}
vector c;int i;
for(i=0;i<size;i++)
c.v[i]=b.v[i]*a;
return c;}
int i;
for(i=0;i<size;i++)
din>>b.v[i];
return(din);}
int i;
for(i=1;i<size;i++)
dout<<")";
return(dout);}
int x[size]={2,4,6};
int main()
cout<<"\n"; cout<<"m="<<m<<"\n";
vector p,q;
q=n*2;
cout<<"\np="<<p<<"\n";
cout<<"q="<<q<<"\n";
getch();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
1. The operator symbol for both prefix(++i) and postfix(i++) are the same
2. Hence, we need two different function definitions to distinguish between them.
3. This is achieved by passing a dummy int parameter in the postfix version.
4. You oyerload the prefix increment operator ++ with either a nonmember function
operator that has one argument of class type or a reference to class type, or with a
member function operator that has no arguments
5. The postfix increment operator ++ can be overloaded for a class type by declaring a
nonmember function operator operator ++ with two arguments, the first having class
type and the second having type int
SOURCE CODE:
#include<iostream>
class Count
private:
int value;
public:
Count() : value(12) {}
void operator ++ ()
++value;
value++;
void display()
int main()
Count count1;
count1++;
count1.display();
++count1;
count1.display();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
1. You overload the prefix increment operator ++ with either a nonmember function
operator that has one argument of class type or a reference to class type, or with a
member function operator that has no arguments
2. The postfix increment operator ++ can be overloaded for a class type by declaring a
nonmember function operator operator++) with two arguments, the first having class
type and the second having type int
3. The postfix operator returns a copy of the value before it was incremented, so it pretty
much has to return a temporary
4. The prefix operator does return the current value of the object, so it can return a
reference to, well, its current value.
SOURCE CODE:
#include<iostream>
class Count {
private:
int value;
public:
Count() : value(78) {}
Count operator ++ () {
Count temp;
temp.value = ++value;
return temp;}
Count temp;
temp.value = value++;
return temp;}
void display() {
};
int main()
result = ++count1;
result.display();
result = count1++;
result.display();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
1. Suppose that we wish to overload the binary operator == to compare two Point objects.
We could do it as a member function or non-member function
2. To overload as a member function, the declaration is as follows
Syntax:
class class_name {
public:
SOURCE CODE:
#include<iostream>
class Distance {
private:
int feet;
int inches;
public:
Distance() {
feet = 0;
inches = 0;}
Distance(int f, int i) {
feet = f;
inches = i;}
feet = D.feet;
inches = D.inches;}
void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;}
int main()
D1.displayDistance();
D2.displayDistance();
D1 = D2;
D1.displayDistance();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
1. These operators can be overloaded globally or on a class-by-class basis.
2. The function call operator () can be overloaded for objects of class type
3. When you overload (), you are not creating a new way to call a function
4. Rather, you are creating an operator function that can be passed an arbitrary number
of parameters.
Syntax:
public:
{ }
};
SOURCE CODE:
#include<iostream>
class Distance {
private:
int feet;
int inches;
public:
Distance() {
feet = 0;
inches = 0;}
Distance(int f, int i) {
feet = f;
inches = i;}
Distance D;
D.feet=a+b+10;
void displayDistance() {
cout << "F: " << feet << " I:" << inches << endl;}};
int main()
D1.displayDistance();
D1 = D2(10,10,10);
D2.displayDistance();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
1. The operator overloading function must preceed with friend keyword, and declare a
function class scope.
2. Friend operator function takes two parameters in a binary operator, varies one
parameter in a unary operator
3. C++ increases the versatility of operator overloading in C++ since functions can be
overloaded as friend functions as well.
4. Friend function can access private members of a class directly
SOURCE CODE:
#include<iostream.h>
#include<conio.h>
class Distance{
private:
int feet;
int inches;
public :
Distance()
feet=0;
inches =0;
feet =f;inches=i;
void displayDistance(){
cout<<"F:"<<feet<<"I;"<<inches<<endl;
return true;
return true;
return false;
};
int main(){
Distance D1(11,10),D2(5,11);
else
getch();
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
1. C++ is able to input and gutput the built-in data types using the stream extraction
operator >> and the stream insertion operator <<.
2. The stream insertion and stream extraction operator can be overloaded to perform
input and output for user-defined types like an object.
3. It is important to make operator overloading funetion a friend of a class because it
would be called without creating an object.
SOURCE CODE:
#include <iostream>
class Distance {
private:
int feet;
int inches;
public:
Distance() {
feet = 0;
inches = 0;
Distance(int f, int i) {
feet = f;
inches = i;
}
output << "F:" << D.feet << " I:" << D.inches;
return output;
};
int main() {
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
4. The postfix expression also known as the primary expression, is a pointer such as
array or identifiers.
5. Second expression is an integral value.
SOURCE CODE:
#include <iostream.h>
#include <conio.h>
class safearay {
private:
int arr[SIZE];
public:
safearay() {
arr[i] = i;
int& operator[](int i) {
return arr[i];
};
int main() {
safearay A;
getch();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
1. The classes istream and ostream define two member functions get() and put()
respectively to handle the single character input/output operations.
2. The get() function reads a single character from the associated stream.
3. The put() function writes to the stream and returns a reference to the stream.
SOURCE CODE:
#include <iostream.h>
#include <conio.h>
int main() {
int count = 0;
char c;
cout << "Enter characters: ";
cin.get(c);
while (c != '\n') {
cout.put(c);
count++;
cin.get(c);
}
cout << "\nNumber of characters: " << count << "\n";
getch();
}
SAVING: F2 ---> FILE6.CPP
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
1. The primary use case of getline() is reading from an input stream in your program.
2. The getline() function does not ignore the leading whitespace characters.
3. So special care should be taken care of about using getline() after cin because cin
ignores whitespace characters leaves it in the stream as garbage.
Syntax :
cin.getline(line,size);
SOURCE CODE:
#include <iostream.h>
#include <conio.h>
int main() {
char city[20];
cin.getline(city, size);
cin.getline(city, size);
getch();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
1. This binary function is used to perform file output operation i.e, to write the objects
into the file, which is stored in the computer memory in the binary form.
2. Only the data member of the object are written and not its member function.
3. It writes the data from a buffer declared by the user to a given device such as a file.
4. This is a primary way to output data from a file.
Syntax :
cout.write(line,size);
1. The first argument, line represents the name of the string to be displayed.
2. Second argument, size represents no.of characters to be displayed.
SOURCE CODE:
#include <iostream.h>
#include <string.h>
#include <conio.h>
int main() {
int i;
int m = strlen(str1);
int n = strlen(str2);
cout.write(str2, i);
cout.write(str2, i);
cout.write(str1, m);
cout.write(str2, n);
getch();
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
The `std::ostream::width` function allows you to specify the minimum width of the output
field. If the data being output is narrower than the specified width, the stream will pad the
output with fill characters (by default, spaces) to reach the specified width.
You can also reset the width to its default by calling `std::ostream::width(0)`, or by using
the `std::setw(0)` manipulator.
The `width` function is particularly useful when you want to control the alignment and
padding of data in formatted output, such as when displaying tables or columns of data
in a user-friendly manner.
SOURCE CODE:
#include<iostream.h>
int main()
int items[4]={10,8,12,15};
int cost[4]={75,100,60,99};
cout.width(5);
cout<<"ITEMS";
cout.width(8);
cout<<"COST";
cout.width(15);
cout<<"TOTAL VALUE"<<"\n";
for(int i=0;i<4;i++)
cout.width(5);
cout<<items[i];
cout.width(8);
cout<<cost[i];
cout.width(15);
cout<<items[i]*cost[i];
sum+=items[i]*cost[i];
cout<<endl;
cout.width(2);
cout<<sum<<"\n";
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
The precision function is a member function of the std::ostream class that allows you to
control the formatting of floating-point numbers when they are output to the stream. It is
used in conjunction with the insertion operator (<<) to specify the number of decimal
places to be displayed for floating-point values. By default, floating-point values are
displayed with a certain level of precision (usually a few decimal places), but you can use
the precision function to override this default and specify your own precision.
Syntax:
Parameters:
n: An integer that represents the new precision setting. It specifies the number of decimal
places to display for floating-point values. The default precision is typically set to 6.
Return Value:
The precision function returns a reference to the std::ostream object itself, which allows
for chaining multiple output manipulations.
SOURCE CODE:
#include<iostream>
#include<math.h>
int main()
int a;
cout.precision(3);
cout.width(10);
cout<<"VALUE";
cout.width(15);
cout<<"SQRT_OF_VALURE\n";
cout.width(8);
cout<<n;
cout.width(13);
cout<<sqrt(n)<<"\n";
cout.precision(5);
for(int n=1;n<=5;n++)
cout.width(8);
cout<<n;
cout.width(15);
cout<<sqrt(n)<<"\n";
cout<<"\nDefault Setting:\n";
cout.precision(0);
cout<<sqrt(10);
return 0;
EXECUTING: CTRL+F9
DESCRIPTION:
In C++, the fill function is a member of the std::basic_ostream class, which serves as the
foundation for output streams like std::ostream. Its primary purpose is to control the fill
character used for padding when formatting output. Padding is a technique to ensure that
output data is displayed in fields of a specified width, and the fill character is used to
occupy any extra space.
The fill function is utilized by setting the desired fill character, often using a specific
character like '*', and is then combined with other stream manipulators, such as std::setw,
which establishes the field width. This combination enables precise control over how data
is presented. For instance:
In this example, we have set the fill character to '', and the width to 10. Consequently, the
string "Hello" is padded with '' characters to ensure it occupies a field of 10 characters.
The output will appear as "*****Hello."
The fill function is commonly employed when the formatting of text or data in fixed-width
fields is necessary, as it contributes to organized and neatly presented information. Its
flexibility to define the padding character makes it valuable in generating structured tables
and ensuring a consistent appearance in output displays.
SOURCE CODE:
#include<iostream>
int main()
cout.fill('<');
cout.precision(3);
for(int n=1;n<=6;n++)
cout.width(5);
cout<<n;
cout.width(1);
cout<<1.0/float(n)<<"\n";
if(n==3)
cout.fill('>');
cout<<"\npaddng cahnged\n\n";
cout.fill('#');
cout.width(15);
cout<<12.3456789<<"\n" ;
return 0;
OUTPUT:
DESCRIPTION:
Syntax:
SOURCE CODE:
#include<iostream>
#include<math.h>
int main()
cout.fill('*');
cout.width(10);
cout<<"Value";
cout.setf(ios::right,ios::adjustfield);
for(int n=1;n<=10;n++)
cout.setf(ios::internal,ios::adjustfield);
cout.width(20);
cout<<sqrt(n)<<"\n";
cout.setf(ios::scientific,ios::floatfield);
cout<<"\nSQRT(100) = "<<sqrt(100)<<"\n";
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
In C++, unsetf is a member function of the std::ios_base class, used for clearing specific
formatting flags that have been set for input or output streams. This function allows you
to selectively remove one or more formatting flags previously set using the setf function,
restoring the default formatting behavior.
Syntax:
Parameters:
flags: An integer value representing the formatting flags you want to clear. It can be a
single flag or a combination of flags obtained using bitwise OR (|).
Return Value:
unsetf returns a reference to the stream object (e.g., std::ios or std::ostream) on which it
was called. This allows for method chaining.
SOURCE CODE:
#include <iostream>
#include<conio.h>
#include<iomanip.h>
int main() {
float p=6.67676765;
cout.setf(ios::hex,ios::basefield);
cout.setf(ios::right,ios::adjustfield);
cout.setf(ios::scientific,ios::adjustfield);
cout.unsetf(ios::scientific);
cout.unsetf(ios::right);
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
This program uses the following ios class functions and flags:
Functions:
width(int): Used to set the required field width.
fill(char): Used to fill the blank spaces in output with given character.
precision(int): Used to set the number of decimal points to a float value.
setf(format flags): Used to set various flags for formatting output like showbase,
showpos, oct, hex, etc.
unsetf(format flags): Used to clear the format flag setting.
Flags:
showbase: Turns on showbase flag.
showpoint: Turns on showpoint flag.
left: Left-justifies the output.
right: Right-justifies the output.
SOURCE CODE:
#include <iostream>
#include <iomanip>
int main() {
cout.width(10);
cout.fill('*');
cout.width(10);
cout.precision(4);
cout.setf(ios::showpos);
cout.unsetf(ios::showpos);
cout.width(10);
cout.width(10);
return 0;
SAVING: IOS_FUNCTIONS_FLAGS.CPP
EXECUTiING: CTRL+F9
OUTPUT:
DESCRIPTION:
Manipulators in C++ are special functions or objects that can modify the output
behavior of standard stream objects, such as cout and cin. They are used to modify the
formatting of data including field width, precision, alignment, padding, and more.
Manipulators can be applied directly to the output stream using the insertion operator
(<<) to modify the formatting of subsequent output.
setfill(char): Used to fill the blank spaces in output with given character.
SOURCE CODE:
#include <iostream>
#include <iomanip>
int main() {
float pi = 3.14159265358979323846;
cout << "Num: " << setw(6) << setfill('0') << num << endl;
cout << "Pi: " << setprecision(4) << fixed << pi << endl;
cout << "Hex: " << hex << num << endl;
cout << "Oct: " << oct << num << endl;
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
This program defines a user-defined manipulator format that displays a float value in a
predefined format with two decimal places. The manipulator is defined as a function that
takes an ostream object as an argument and returns the same object. The manipulator
is then used to format the output of a float value.
SOURCE CODE:
#include <iostream>
#include <iomanip>
#include <ostream>
output.setf(ios::showpoint);
output<< setprecision(4);
output<< setfill('#');
output.width(10);
return output;
int main() {
return 0;
EXECUTING: CTRL+F9
OUTPUT:
DESCRIPTION:
To create a file in C++, we can use the ofstream or fstream class and specify the name of
the file. We can then write to the file using the insertion operator (<<).
This program creates a file named filename.txt and writes a line of text to it. The
ofstream class is used to create and open the file, and the insertion operator (<<) is used
to write to the file. The close() function is used to close the file.
SOURCE CODE:
#include <iostream>
#include <fstream>
int main() {
ofstream MyFile("filename.txt");
MyFile.close();
return 0;
SAVING: FILECREATION.CPP
EXECUTING: CTRL+F9
FILE CONTENT:
DESCRIPTION:
Here the program explains about reading the files one after another. Here two text files
are created 1. state.txt and 2. capital.txt in the first text file content called Goa,
TamilNadu and Arunachal Pradesh are written by the user and in the second text file
content called Patna, Chennai and Itanagar are written by the user. And then reading
the files one after another and saving into the text files
SOURCE CODE:
#include <iostream>
#include <fstream>
int main()
ifstream file1("state.txt");
ifstream file("capital.txt");
ofstream kout;
kout.open("state.txt");
kout<<"Goa";
kout<<"TamilNadu";
kout<<"Arunachal Pradhesh";
kout.close();
kout.open("capital.txt");
kout<<"Patna";
kout<<"Chennai";
kout<<"Itanagar";
kout.close();
char word[size];
ifstream kin;
while(kin)
kin.getline(word,size);
cout<<word<<endl;
kin.close();
kin.open("capital.txt");
while(kin)
kin.getline(word,size);
coutt<<word<<endl;
kin.close();
return 0;
SAVING: READINGFILE.CPP
EXECUTING: CTRL+F9
FILE CONTENT:
STATE FILE:
CAPITAL FILE:
DESCRIPTION:
Two files can be read simultaneously.The function getline() reads characters from input
stream and appends it to the string object until the delimiting character is encountered.
syntax:
SOURCE CODE:
#include<iostream>
#include<fstream>
#include<stdlib.h>
int main()
char line[size];
ifstream fin1,fin2;
fin1.open("state.cpp");
fin2.open("capital.cpp");
for(int i=0;i<3;i++){
if(fin1.eof()!=0)
exit(1);
fin1.getline(line,size);
cout<<"capital of "<<line;
if(fin2.eof()!=0)
exit(1);
fin2.getline(line,size);
cout<<"-"<<line<<endl;
return 0;
SAVING: CAPITAL.CPP
EXECUTiING: CTRL+F9
OUTPUT:
put().
DESCRIPTION:
The functions get() and put() are byte-oriented (single character at a time ).That is, get()
will read a byte of data and put() will write a byte of data.The get has many forms,but the
most commonly used version along with put() is
SOURCE CODE:
#include<iostream>
#include<fstream>
#include<string.h>
int main()
int i,len;
char string[50],ch;
cin.get(string,50);
len=strlen(string);
ofstream fout;
fout.open("info.txt",ios::out);
for(i=0;i<len;i++)
fout.put(string[i]);
fout.close();
ifstream fin;
while(fin.get(ch))
cout<<ch;
fin.close();
return 0;
SAVING: I/O_MODE.CPP
EXECUTiING: CTRL+F9
OUTPUT:
DESCRIPTION:
To write blocks of binary data, we use c++’s read() and write() functions.
Funtion takes two arguments.The first is address of variable buf and second is the length
of the variable in bytes.
SOURCE CODE:
#include<iostream>
#include<fstream>
int main()
int arr[30],i,n,a,arr2[30];
cin>>n;
for(i=0;i<n;i++)
cin>>arr[i];
ofstream fout;
fout.open("array.bin",ios::binary);
fout.write((char*)(arr),sizeof(arr));
fout.close();
fin.open("array.bin",ios::binary);
fin.read((char*)arr2,sizeof(arr2));
for(i=0;i<n;i++)
cout<<arr2[i]<<" ";
fin.close();
return 0;
SAVING: BINARY_FILES.CPP
EXECUTiING: CTRL+F9
OUTPUT:
DESCRIPTION:
The functions read() and write() can also be used for reading and writing class objects.
Syntax:
read((char*)&obj,sizeof(obj));
write((char*)&obj,sizeof(obj));
SOURCE CODE:
#include <iostream>
#include <fstream>
class Student {
public:
char name[size];
int rollNumber;
Student() {}
for(int i=0;i<size;i++)
name[i]=n[i];
rollNumber=rn;
void display() {
int main() {
char name[size];
int rll;
cin.get(name,size);
cin>>rll;
Student student1(name,rll);
ofstream outFile;
outFile.open("student.dat", ios::out);
outFile.write((char*)(&student1), sizeof(Student));
outFile.close();
Student student2;
ifstream inFile;
inFile.open("student.dat", ios::in);
inFile.read((char*)(&student2), sizeof(Student));
inFile.close();
student2.display();
return 0;
SAVING: FILEMODE.CPP
EXECUTiING: CTRL+F9
DESCRIPTION:
File can be opened using various modes.The mode can combine two or more parameters
Syntax:
stream_obj.open(“file_name.ext”,mode);
SOURCE CODE:
#include<iostream>
#include<fstream>
int main()
char line[50];
ifstream fin;
fin.open("text.cpp",ios::ate);
fin.close();
fin.open("text.cpp",ios::in);
fin.getline(line,50);
fin.close();
ofstream fout;
fout.open("text.cpp",ios::trunc|ios::out);
cout<<"deleted content(ios::trunc)"<<endl;
fout.close();
fin.getline(line,50);
fin.close();
fout.open("text.cpp",ios::out|ios::nocreate);
fout.close();
fout.open("text.cpp",ios::noreplace);
fin.getline(line,50);
cout<<line<<endl;
fout.close();
fin.close();
return 0;
SAVING: FILEMODE.CPP
EXECUTiING: CTRL+F9
OUTPUT:
DESCRIPTION:
Random access of files in C++ refers to the ability to directly access and modify specific
locations within a file, rather than just reading or writing sequentially from the beginning
to the end. It allows you to efficiently work with large files or update specific portions of a
file without processing the entire file. Random access is especially useful for tasks like
updating records in a database file, managing binary data, or implementing custom file
formats.
Here are some key points about random access of files in C++:
File Opening Modes:
To perform random access, you need to open the file in both input (std::ios::in) and output
(std::ios::out) modes using an std::fstream object. This combination enables both reading
and writing within the same file.
C++ provides functions like seekp() and seekg() for controlling the file pointer. These
functions allow you to move the file pointer to a specific position within the file. For
example, you can set the position based on a byte offset from the beginning of the file or
the end of the file.
With random access, you can read or write data at any location within the file. This means
you can overwrite or update existing data, append new data, or insert data at specific
positions.
Efficiency:
Random access can be more efficient than reading the entire file sequentially when you
only need to modify or retrieve a small portion of the data. It can save both time and
system resources.
Random access is commonly used when working with binary files that store complex data
structures or custom file formats. You can directly access and manipulate binary data
within the file.
Syntax:
seekp(offset,reference_position);
tellp();
#include<iostream>
#include<fstream>
#include<cstring>
int main()
char ch[150],str;
int i,pos,length,len;
cin.get(ch,150);
length=strlen(ch);
fstream file;
file.open("text.cpp",ios::out|ios::trunc);
for(i=0;i<length;i++)
file.put(ch[i]);
file.seekp(-5,ios::end);
file<<"hardware";
file.close();
ifstream file1;
file1.open("text.cpp");
file1.seekg(5,ios::beg);
cout<<"\n position="<<file1.tellg();
while(file1)
file1.get(str);
if(file1.eof())
break;
cout<<str<<endl;
file1.close();
return 0;
EXECUTING: CTRL + F9
OUTPUT:
DESCRIPTION:
In C++, file pointer manipulation is a fundamental aspect of working with files. File
pointers are used to navigate and read or write data within a file. Here's a brief description
of how file pointer manipulation works in C++.File pointer manipulation is essential for
various file operations, such as reading and writing data at specific locations, appending
to existing files, or updating file contents. Proper handling of file pointers helps you control
the flow of data in your file operations.
Syntax:
seekg(offset,reference_position);
seekp(offset,reference_position);
tellg();
tellp();
SOURCE CODE:
#include<iostream>
#include<fstream>
#include<cstring>
int main()
char ch[100];
int i,pos,length;
cin.get(ch,100);
length=strlen(ch);
fstream file;
file.open("text.cpp",ios::in|ios::out|ios::trunc);
for(i=0;i<length;i++)
file.put(ch[i]);
file.tellg();
cin>>pos;
file.seekg(pos,ios::beg);
file.tellg();
file.getline(ch,50);
cout<<ch<<endl;
file.close();
return 0;
EXECUTING: CTRL + F9
OUTPUT:
DESCRIPTION:
In C++, the seekg and seekp functions are used to set the cursor position within a file.
These functions are typically used with file stream objects (ifstream and ofstream) for input
and output operations, respectively. Here's a description of seek actions in C++:
seekg stands for "seek get" and is used with input file streams (e.g., ifstream).
It allows you to set the position of the file cursor for reading (getting) data from a file.
The seekg function takes two arguments: an offset and a seek direction (from the current
position, from the beginning, or from the end).
Syntax:
The tellg function can be used to determine the current cursor position within the file.
SOURCE CODE:
#include <iostream>
#include <fstream>
#include <cstring>
int main() {
char str[80];
cin.getline(str, 80);
ofstream file1("hello.cpp");
if (!file1) {
return 1;
file1.put(str[i]);
file1.close();
ifstream file("hello.cpp");
if (!file) {
return 1;
file.seekg(0, ios::beg);
cout << "Position after seeking to the beginning: " << file.tellg() << endl;
file.seekg(4, ios::cur);
cout << "Position after seeking forward by 4 characters: " << file.tellg() << endl;
file.seekg(0, ios::cur);
cout << "Position after seeking 0 characters: " << file.tellg() << endl;
file.seekg(-1, ios::cur);
cout << "Position after seeking back by 1 character: " << file.tellg() << endl;
file.seekg(0, ios::end);
cout << "Position after seeking to the end: " << file.tellg() << endl;
file.seekg(-3, ios::end);
cout << "Position after seeking back by 3 characters from the end: " << file.tellg()
<< endl;
file.close();
return 0; }
EXECUTING: CTRL + F9
OUTPUT:
FILE CONTENT:
SOURCE CODE:
#include <iostream.h>
#include <fstream.h>
#include<string.h>
#include<conio.h>
int main()
char string[100], c;
int i, length;
clrscr();
cin.get(string, 100);
length = strlen(string);
fstream file;
file.put(string[i]);
file.close();
file.open("cme.txt", ios::in);
cout << c;
file.close();
getch();
return 0;
EXECUTING: CTRL + F9
OUTPUT:
FILE CONTENT: