please help me how to take input from .txt file in a program,and how to write output in a .txt file.
Taking input from and writing output in .txt file in a c++ program is very simple,
just add these following two lines in the beginning of the main program.
freopen("input.txt","r",stdin);//redirects standard input freopen("output.txt","w",stdout);//redirects standard output
Now, all input data will be taken from input.txt file
and all output data will be written into output.txt file.
sample program-
#include<iostream>
using namespace std;
int main()
{
freopen("input.txt","r",stdin);//redirects standard input
freopen("output.txt","w",stdout);//redirects standard output
int x;
cin>>x;//reads from input.txt
cout<<x<<endl;//writes to output.txt
return 0;
}
Hope ,this is helpful.
If you still don’t get anything ,feel free to ask.
The question has been asked before. Take a look here and here. Also check here. In my opinion stream redirection from the console is the easier way because the code does not need to be changed, however both will serve the purpose and what you prefer is your choice.
if you are using turbo c++ complier than follow the following steps:
-
Use fstream.h header file (like : #include<fstream.h> )
-
for save or give input into file
Example :
ofstream fo; // used to open files
fo.open(“Myfile.txt”,ios::out); //used to initialized file with any name
fo<<text<<"\n"; // Insert text or data
fo.close(); // used to close files
- for Print data from file
Example :
ifstream fi; // used to open files
fi.open(“Myfile.txt”,ios::in); //used to initialized file with any name
while(!fi.eof())
{
fi>>text; // Read text or data
cout<<text;
}
fi.close(); // used to close files
It is Not in Details
if You want To See More Details
Right Click in Turbo c++ compiler
and type fstream (without click any more …)
now select fstream.h from options and read full details about this header file
and abouts its function