Saturday, September 10, 2011

How to read input from a .txt File

Reading input from the standard input device i.e keyboard is what we have done so far. We use input stream variable ‘cin’ for this purpose and user can enter his desired character or integer as an input to our program. What if we want to read the input from a text file? Lets see what we can do for this:

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

Step 2: Declare the input variable say ‘in’ using ifstream. It would be like ‘ifstream in;’. (We use ifstream for input variables and ofstream for output variables.)

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

Step 4: Now where ever in your program you want to read input from the file, you would use ‘in’ in place of ‘cin’.

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


Example Source Code:
#include<iostream>
#include<fstream>
using namespace:std;
int main (void)
{
int x;
ifstream in;
in.open(“MyFile.txt”);
in>>x;
cout<<”The first integer in your file is ”<<x<<endl;
in.close();
return 0;
}


REMEMBER:
1. 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.
2. Always have something written in your file otherwise it will give you garbage as input.


0 response(s):

Respond to this Post

Your participation is appriciated...