Group
File Management in C++
Objective
1. Open an existing text file for reading using `ifstream`.
2. Read the file line by line.
3. For each line, use a `stringstream` to extract words.
4. Count the total number of words.
5. Display the total count on the screen.
Implement a program that counts the words in a text file.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include for standard input and output
#include <fstream> // Include for file input stream
#include <sstream> // Include for stringstream
#include <string> // Include for using the string class
using namespace std;
int main() {
ifstream file("sample.txt"); // Open the file 'sample.txt' for reading
string line; // Variable to hold each line from the file
int wordCount = 0; // Counter to track total number of words
// Check if the file was opened successfully
if (file.is_open()) {
// Read the file line by line
while (getline(file, line)) {
stringstream ss(line); // Create a stringstream for the current line
string word; // Variable to store individual words
// Extract words from the line
while (ss >> word) {
wordCount++; // Increment the word counter for each word
}
}
file.close(); // Close the file after reading
// Output the total number of words
cout << "Total number of words in the file: " << wordCount << endl;
} else {
// Display error message if file couldn't be opened
cout << "Error: Could not open file." << endl;
}
return 0; // End of program
}
Output
//Output Example:
Total number of words in the file: 42
//Content of sample.txt (for reference):
This is a sample text file.
It contains several lines of words.
The program should count them all correctly.