How do I count words in a File (I'm New)

I try to set up the code but the infile will not open and read. I need to set up the input file and ask the user for the input file name.


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


using namespace std;



//Function prototypes
int CountWords(char, int);


int main()
{

string words, str;
int choice;
int count, i;
char word;

cout << setprecision(2);
cout << fixed << showpoint;

ifstream inFile;

do
{
cout << " 1. Count Words In a File" << endl;
cout << " 2. Count Characters In a File" << endl;
cout << " 3. Sum Integers In a File" << endl;
cout << " 4. Average Integers In a File" << endl;
cout << " 5. Maximum Integers In a File" << endl;
cout << " 6. Minimum Integers In a File" << endl;
cout << " 7. Longest Word In a File" << endl;
cout << " 8. Quit" << endl;
cout << endl;
cout << "Choice : ";
cin >> choice;
cout << endl;


switch(choice)
{
case 1:



cout << " Enter the input file name : " << endl;
cin >> words;

count = CountWords(word, count);

if (count != 0)
{

cout << " Word Count = " << count << endl;
}


break;

case 8:
cout << "Thank you -- Goodbye!" << endl;
cout << endl;
break;

default:
cout << "Invalid Option -- Try Again!" << endl;
cout << endl;

break;
}


}while(choice != 8);

inFile.clear();
inFile.close();





return 0;
}


// ************** function definitions go here ***********************

int CountWords(char word, int count)
{
string words;
ifstream inFile;
inFile.open(words.c_str());

inFile >> word;
while(!inFile)
{
cout << "Error opening input file -- Please try again!" << endl;
}

count = 0;
word = 0;
while(inFile >> word)
{
if (word =! " " & count < 10000)
{
count ++;
}

cout << count;
inFile >> word;


}
inFile.close();
inFile.clear(); \

return count;
}


I can't remember exactly how to do it but the best way to count words for me is actually counting the spaces. So if you read one character at a time you can count all of the spaces, tabs, and new lines. But you have to do some error checking to handle 2 spaces next to each other but it should be relatively easy.

inf.unsetf(ios::skipws);

This makes it so when you read in a character it doesn't skip the spaces.

Good luck,
Yoshi
@Yoshi... what if there happens to be more than one space between two words?

@op: I see several problems right off the bat. For now, please edit your post and use code tags... [ code ] [ /code ]

(I'm sorry, I'm extremely lazy)
Last edited on
Topic archived. No new replies allowed.