SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
I/o Streams As An Introduction To Objects And Classes
Exercise:
Programming Projects
Question:20 | ISBN:9780321531346 | Edition: 7

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.