Program 7,8,9,10
Program 7,8,9,10
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
string data;
fstream file;
file.open("abc.txt",ios::out);
//writing to a file
file<<"welcome to c++ programming";
file.close();
while(getline(file,data)){
cout<<data<<endl;
}
file.close();
return 0;
}
Output:
welcome to c++ programming
program 8:
#include <iostream>
#include <fstream>
using namespace std;
void writefile(int h,int m,int s)
{
char str[10];
fstream file;
file.open("abc.bin",ios::out|ios::binary);
sprintf(str,"%d:%d:%d",h,m,s);
file.write(str,sizeof(str));
file.close();
}
void readfile()
{
char str[10];
fstream file;
file.open("abc.bin",ios::out|ios::binary);
file.read(str,sizeof(str));
file.close();
cout<<str;
}
int main()
{
int m,h,s;
cout<<"enter time\n";
cout<<"enter hour";
cin>>h;
cout<<"enter min";
cin>>m;
cout<<"enter sec";
cin>>s;
writefile(h,m,s);
readfile();
return 0;
}
Output:
Enter time
Enter hour 10
Enter min 20
Enter sec 30
10:20:30
Program 9:
#include<iostream>
#include<exception>
using namespace std;
int main(){
int x,y;
cout<<”enter x and y”;
cin>>x>>y;
try{
divide(x,y);
}
catch(int i){
cout<<”Divide by zero exception occurred”;
}
return 0;
}
Output:
enter x and y10
0
Divide by zero exception occurred
Program 10:
#include <iostream>
#include <exception>
using namespace std;
int main()
{
int a[10],i,size;
try
{
cout<<"Enter array size:"<<endl;
cin>>size;
if (size>10) throw 5;
if (size<=0) throw 3.2;
cout<<"Enter array elements"<<endl;
for (i=0;i<size;i++)
cin>>a[i];
cout<<"Array elements are:"<< endl;
for (i=0;i<size;i++)
cout<<a[i]<<" ";
}
catch (int x)
{
cout<<"Array size out of bounds exception occured"<<endl;
}
catch (double y)
{
cout<<"Neagative array size exception occured"<<endl;
}
return 0;
}
Output 1:
Enter array size:
5
Enter array elements
1
2
3
4
5
Array elements are:
12345
Output 2:
enter array size:
20
Array size out of bounds exception occurred
Output 3:
Enter array size:
-9
Neagative array size exception occured