Ifstream C++
Step 1: Include header file fstream
To use ifstream to read from file, just include fstream header file at top (like iostream) as below
Step 2: Create object of input file stream (ifstream)
Below line is used to create object of ifstream (input file stream)
Here ifile is an object of ifstream and we can use this object to perform all input file operations.
Step 3: Open text file and read data
Using dot operator (.), we can call open() method associated with object ifile. Below line is used to do this.
First parameter of open method is text file name. You may provide complete address of location where file is located.
Second parameter is file opening mode. There is only one option to open file for reading data which is
- ios::in To read data from file
This is default mode to open file for reading purpose so it is optional. If you don't write ios::in then compiler include it by default.
Step 4: Read data from file
To read complete line from file, we use a method getline(). This methods takes two parameters.
First Parameter is the object of ifstream which is ifile. It reads complete line from file and copy it to second parameter which is a string named country. We can display this string country.
Step 5: Close the file
Don’t forget to close file at the end of program so that resources allocated to ofstream can be de-allocated by the operating system.
Below is a complete C++ program to read data from text file
Ifstream C++ |
Ifstream C++ output |
Post a Comment