Write a program that prompts the user to input the name of a text file and then outputs the number of words in the file. You can consider a “word” to be any text that is surrounded by whitespace (e.g., a space, carriage return, newline) or borders the beginning or end of the file.
PROGRAM CODE:
//Header file section
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
// Function to count the number of words in a given text
int countWordsInText(const string& text) {
istringstream iss(text);
string word;
int wordCount = 0;
// Loop through each word in the text
while (iss >> word) {
wordCount++;
}
return wordCount;
}
int main() {
string filename;
// Ask the user to input the name of the text file
cout << "Enter the name of the text file: ";
cin >> filename;
// Open the file for reading
ifstream inputFile(filename);
// Check if the file was opened successfully
if (!inputFile) {
cerr << "Error: Unable to open the file." << endl;
return 1;
}
// Read the entire content of the file into a string
stringstream buffer;
buffer << inputFile.rdbuf();
string fileContent = buffer.str();
// Close the file
inputFile.close();
// Count the number of words in the file content
int wordCount = countWordsInText(fileContent);
// Output the result
cout << "Number of words in the file: " << wordCount << endl;
return 0;
}
DATA IN INPUT FILE(inputFile.txt):
Hello Martin How are you
OUTPUT:
Enter the name of the text file: inputFile.txt
Number of words in the file: 5