- Include the
fstreamlibrary. - Create an
ifstreamobject. - Open the file with
.open() - Read the file
a. Usegetline()to read line by line
b. Use>>to read word by word - Close the file with
.close()
Example:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Opens the file
ifstream inFile;
inFile.open("data.txt");
// Varifies the file exists
if (!inFile.is_open())
return 0;
// Iterates through every line in the file
string line;
while (getline(inFile, line)){
// Do something here, such as printing the line:
cout << line << endl;
}
// Closes the file
inFile.close();
return 0;
}