How to open a file and count the # of words? Need help!!

So I need to write a program that opens a file (which ever file the user inputs) and count the number of words example file: This &%file should!!,...



have exactly 7 words.

The if statment nested in the while loop near the bottom will give me the correct word count but only display the first character of the file, and if i comment out the if statement it doesnt count the words but it displays the file content correctly. I need it to do both. please help me. Here is my code..

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
char inChar;
ifstream inFile;
int count=1;
string fileName;

cout << endl;
cout<<"Enter filename"<<endl;
cin>>fileName;
string word;

while(fileName != "quit")
{
inFile.open(fileName.c_str());
if (!inFile)
{
cout << "Can't open the input file.";
return 1;
}

inFile.get(inChar);
inFile>>word;

while(inFile)
{
cout << inChar;
inFile.get(inChar);

if(inFile>>word)
count++;
}

cout << endl << "This file has " << count << " words." << endl;
inFile.close();
count=1;

cout <<endl;
cout<<"Enter filename"<<endl;
cin>>fileName;


}
return 0;
}


Last edited on
I am not sure what do you want exactly the file example isn't clear. Anyway here is what I think you want :

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
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream inFile;
    int count=0;
    string fileName="", word="";

    while (1)
    {
        cout << endl <<"Enter filename" << endl;
        cin >> fileName;

        if (fileName == "quit")
            break;

        inFile.open(fileName);

        if (!inFile)
        {
            cout << "Can't open the input file.";
            return 1;
        }

        while (inFile >> word)
        {
            cout << word << '\n';
            count++;
        }

        cout << endl << "This file has " << count << " words." << endl;
        inFile.close();
        count = 0;
    }

    return 0;
}


using inFile.get(inChar) will store a char in (inChar) but you want to count the words not letters, here get function takes a char but it doesn't take a string, so you use inFile >> word this will store a string or a char think of it as cin >> word. In your code you are using both when you should use only one, and in your case you should use inFile >> word where word is a string.
Topic archived. No new replies allowed.