Monday, September 12, 2011

How to write to a .txt file

In the last post I told you how to read input from a .txt file. Lets see how can we save output in a .txt without displaying it on the screen.

Step 1: Include the header file ‘fstream’ which is used for declaring the input/output stream variables.

Step 2: Declare the output variable say ‘out’ using ofstream as ‘ofstream out;’. (We use ofstream for output variables and ifstream for input variables.)

Step 3: Open the file you want to read the input from using the command ‘out.open(“yourfilename.txt”);’.

Step 4: Now where you want to output something to the file just use 'out' in place of 'cout'.

Step 5: Close the file at the end of your program with ‘out.close();’.


Example Source Code:
#include<iostream>
#include<fstream>
using namespace:std;
int main (void)
{
int x;
x=1;
ofstream out;
out.open(“MyFile.txt”);
out<<x;
cout<<”Value of x has been written in your file. "<<endl;
out.close();
return 0;
}


REMEMBER:
         Always keep your .txt file in the same directory as your .cpp file or otherwise you would have to give complete address of the file while opening it.


0 response(s):

Respond to this Post

Your participation is appriciated...