Group
File Management in C++
Objective
1. Create or ensure a text file exists with multiple lines of content.
2. Use `ifstream` to open the file for reading.
3. Read each line using a `while` loop and the `getline()` function.
4. For every line read, increment a counter.
5. Once the end of the file is reached, display the total line count.
6. Properly close the file after reading is complete.
Write a program that calculates the number of lines in a text file.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include for console input and output
#include <fstream> // Include for file stream operations
#include <string> // Include for using the string class
using namespace std;
int main() {
string fileName = "example.txt"; // Name of the file to be read
ifstream inFile(fileName); // Open the file for reading
string line; // Variable to hold each line of text
int lineCount = 0; // Counter to keep track of the number of lines
// Check if the file was successfully opened
if (!inFile) {
cout << "Error: Could not open the file." << endl;
return 1; // Exit with an error code
}
// Read the file line by line
while (getline(inFile, line)) {
lineCount++; // Increment the counter for each line read
}
inFile.close(); // Close the file
// Output the result to the user
cout << "The file contains " << lineCount << " lines." << endl;
return 0; // End of program
}
Output
The file contains 7 lines.