Detailed explanation of how to use the ifstream object in C++ for input files.
ifstream is a class in the C++ standard library that is used to read data from files. It provides a range of functions and operators for opening files, reading data, and manipulating file pointers. This is a detailed explanation of how to use ifstream.
- Header file for the ifstream class:
#include - Create an ifstream object:
ifstream inputFile; - Open a file:
inputFile.open(“filename”);
or
inputFile.open(“filename”, ios::in);
The “filename” here is the name of the file to be read. - Check if the file has been successfully opened.
- if the input file is open {
// the file is opened successfully
} else {
// the file failed to open
} - Read data from a file.
- Read an integer from the input file and store it in the “data” variable.
- Alternatively
- Capture a line of text from the inputFile and store it in the variable line.
- The first option can be used to read basic data types such as integers and floating point numbers, while the second option can be used to read strings.
- Close the file:
inputFile.close();
The above is the basic usage of ifstream, below are some commonly used member functions:
- good(): Check if the file has been opened successfully.
- eof(): check if the end of the file has been reached.
- fail(): Check for read failure.
- clear(): Clears the error status flag.
- skip(n, delim) : Skip iteration over n characters or until encountering the delimiter delim.
Example code:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream inputFile;
inputFile.open("input.txt");
if (inputFile.is_open()) {
int data;
while (inputFile >> data) {
cout << data << " ";
}
inputFile.close();
} else {
cout << "File open failed." << endl;
}
return 0;
}
The above is a detailed explanation of the basic usage of ifstream and some commonly used operations functions. Using ifstream makes it easy to read data from files.