Program to Create and display data of a file- Shows Error

Guys, i have made this program to create and display data of that file. But it is not working as i expected. So it would be really helpful for me if someone helps me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include<iostream.h>
#include<fstream.h>
void main()
{
ofstream fout("student");
char ch ='y';
while(ch=='y'||ch=='Y')
{
cin>>ch;
fout<<ch;
cout<<"Yes or NO";
cin>>ch;
}
ifstream fin("school",ios::in);
while(fin)
{
fin>>ch;
cout<<ch;
}
fin.close();
}

Ok, what is 'expected' from this?

The files you are opening have to exist beforehand, and you did not specify the file extension. So the files will not open. You should perform a check that the files are open. fout.is_open(), fin.is_open(). So, if the user enters Y or y, it will just ask him again. Is that what is intended?

There are some other design flaws, but for now, those are good.

Glad to see a new member! Welcome to the forum, Sainatarajan!
The thing is i want to create a file and put some data in it and display those data.
Like so:
 
ostream fout("student.txt", ios::out);


As well, iostream.h and fstream.h are not the correct files to use. Use iostream, and fstream.
Like so:
1
2
#include <iostream>
#include <fstream> 


As well, if you want "school"(You probably want "school.txt") to exist, you need to create it first. Use a fstream instead of an istream in this case, and open the file with the ios::out flag set as well.

fstream fin("school.txt", ios::out | ios::in);

Also, you need to put

using namespace std; after your includes, otherwise, you must specify std:: before all your standard objects.

And fout never gets closed.
Last edited on
Topic archived. No new replies allowed.