-1

I'm writing a program that is supposed to get the word count of the passage using a text file. I am only able to get my program to grab the character count, rather than the word count. I am not sure on what I can do to fix the program.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    string gettysburg_address;
    string constitution_preamble;
    string file;
    string words;
    string someMoreWords;
    int count = 0;
    ifstream fin("gettysburg_address.txt");
    ifstream con("constitution_preamble.txt");

    gettysburg_address = "gettysburg_address.txt";
    constitution_preamble = "constitution_preamble.txt";

    words = fin.get();
        
    someMoreWords = con.get();
    
    while (true) {
        cout << "Enter your file name or type 'end' if you would like to stop: ";
        cin >> file;

        if (file == "gettysburg_address.txt") {
            while (!fin.eof()) {
                words = fin.get();
                count++;
            }

            cout << "The word count of this document is: " << count << endl;
            cout << endl;
            count = 0;
        }
        else if (file == "constitution_preamble.txt") {
            while (!con.eof()) {
                someMoreWords = con.get();
                count++;
            }

            cout << "The word count of this document is: " << count << endl;
            cout << endl;
            count = 0;
        }
        else {
            cout << "Not a valid input. Please try the name of a text file." << endl;
            cout << endl;
        }
        
        if  (file == "end") {
            return 0;
        }
    }
}
genpfault
  • 51,148
  • 11
  • 85
  • 139
  • 4
    `while (!fin.eof())` -- [See this](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – PaulMcKenzie Aug 31 '23 at 16:20
  • 1
    Chris pointed out the underlying issue with your code. [Here is an example](https://pastebin.com/Ppxi2bQA) for a simple word counter in C++. It only respects letters so "Hello it's me, your buddy clark!" gives a word count of 6. – Stuntman11 Aug 31 '23 at 21:02

1 Answers1

1

The get member function on a input file stream only gets a character. This is why you're getting a character count. If you wish for a word count, a simple approach would be to create a std::string and extract from the input stream into that string repeatedly.

std::string word;
fin >> word;

This of course is a very simple approach, and for complex texts may not return an accurate word count. For those a more sophisticated parsing technique may be required.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • ...with the proviso that this will count something like `A - B` as three words, so you may want to do a little checking on what it's counting as a word. – Jerry Coffin Aug 31 '23 at 16:42