Reading + counting from files

I'm trying to make a program that prints out the file data and number of words in a file of text. The number of words is defined by whether there is a space or not; so "ghm...y&hfd" is one word whereas "hello guys" is two words. I'm having trouble with the logic behind the word counting, I keep getting a count of 0 when I execute this but idk why. Also, can't figure out how to print the file data and would like help. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <fstream>
#include <cassert> // assert

using namespace std;

int main()
{  
    int count = 0;
    string fileName; // Input file name
    char prevChar;             // Last character read
    char currChar;             // Character read in this iteration
    ifstream inFile; // Input file stream
    
    // Prompt
    cout << "Enter a filename or type quit to exit: ";
    cin >> fileName;
    
    //when user does not want to exit program
    
    while (fileName != "quit")
    {
        // Open file
        inFile.open(fileName.c_str());
        
        //make sure it is open
        assert(inFile);
        
        inFile.get(prevChar);       // Initialize previous value
        inFile.get(currChar);       // Initialize current value
        while (inFile)                   // While input succeeds . . .
        {
            if ((currChar != ' ' &&    // Test for !=
                prevChar == ' '))
                count ++;
            if ((currChar == ' ' && prevChar != ' '))
                count++;                // Increment counter
            prevChar = currChar;      // Update previous value to current
            inFile.get(currChar);     // Get next value
        }
        cout << "Number of words in file: " << count << endl;
        
                 // Calls needed to reuse ifstream variable
         inFile.close();
         inFile.clear();
     
        // Again?
        cout << "Enter the name of the file "
        << "(type quit to exit): ";
        cin >> fileName;
        
        
    }
    else return 0;
return 0;
Are you allowed to use >> to read the input ?
In this case it's really simple:
1
2
3
4
5
6
ifstream src("YourFileName");
// check if stream is valid
string word;
int count = 0;
while(src >> word)
  count++;
Topic archived. No new replies allowed.