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 ‘“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:
using namespace:std;
int main (void)
int x;
ifstream in;“MyFile.txt”);
cout<<”The first integer in your file is ”<<x<<endl;
return 0;

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...