Pages

100 Contemporary Living Room Designs

Friday, March 29, 2013

C++ File Handling Program

Write a program that shows the use of read() and write() to handle file I/O involving objects.

#include<iostream.h>
#include<fstream.h>
#include<iomanip.h>
class INVENTORY
{
  char name[10];
  int code;
  float cost;
  public:
    void readdata(void);
    void writedata(void);
};
void INVENTORY :: readdata(void)
{
  cout<<"\n Enter name:";cin>>name;
  cout<<"\n Enter code:";cin>>code;
  cout<<"\n Enter cost:";cin>>cost;
}
void INVENTORY :: writedata(void)
{
  cout<<setiosflags(ios::left)
  <<setw(10)<<name
  <<setiosflags(ios::right)
  <<setw(10<<code)
  <<setprecision(2)
  <<setw(10)<<cost<<endl;
}

int main()
{
  INVENTORY item[3];
  fstream file;
  file.open("Stock.dat",ios::in|ios::out);
  cout<<"\n Enter details for three items \n";
  for(int i=0;i<3;i++)
  {
    item[i].readdata();
    file.write((char *) & item[i],sizeof(item[i]));
  }
  file.seekg(0);
  cout<<"\nOutput\n";
  for(i=0;i<3;i++)
  {
    file.readdata((char *) &item[i],sizeof(item[i]));
    item[i].writedata();
  }
  file.close();
  return 0;
}


C++ PROGRAM TO DO ELECTRICITY BILL CALCULATION.

C++ PROGRAM TO READ AND DISPLAY STUDENT DETAILS USING INHERITANCE.

C++ program to overload the unary minus operator using friend function.

Write a program to overload the unary minus operator using friend function.

#include<iostream>
using namespace std;
class space{
  int x;
  int y;
  int z;
  public:
    void getdata(int a,int b,int c);
    void display(void);
    friend void operator-(space &s);
};
void space :: getdata(int a,int b,int c){
  x=a;
  y=b;
  z=c;
}
void space :: display(void){
  cout<<x<<" ";
  cout<<y<<" ";
  cout<<z<<"\n";
}
void operator-( space &s){
  s.x=-s.x;
  s.y=-s.y;
  s.z=-s.z;
}
int main(){
  space s;
  s.getdata(10,-20,30);
  cout<<"S : ";
  s.display();
  -s;
  cout<<"S :";
  s.display();
  return 0;
}

You might also like:

C++ PROGRAM TO DO ELECTRICITY BILL CALCULATION.

C++ PROGRAM TO READ AND DISPLAY STUDENT DETAILS USING INHERITANCE.

OUTPUT

 


Template Function

Write a template function that swaps the values of two arguments passed to it. In main( ), use the function with integers and characters.

#include<iostream.h>
using namespace std;
template <class T>
void swap(T &a,T &b)
{
    T temp=a;
    a=b;
    b=temp;
}
void func(int x,int y,char w,char z)
{
    cout<<"x and y before swap: "<<x<<y<<"\n";
    swap(x,y)
    cout<<"x and y after swap: "<<x<<y<<"\n";
    cout<<"w and z before swap: "<<w<<z<<"\n";
    swap(w,z)
    cout<<"w and z after swap: "<<w<<z<<"\n";

}
int main()
{
    fun(10,20,’s’,’S’);
    return 0;
}



You might also like:-