Trying to count words C++

Hey, I am trying to do a word counter and am stuck... The object of this assignment is to

1. read the document and count the words
2. output the words
3. let user input document name.

basically, we are given a few text files and we are supposed to open them, read them and count the words. I get that i can count the spaces in between the words and figure out the number of words from that. I guess i will have to add 1 to the number of spaces.
Here is what i have so far.

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

using namespace std;

int main(){
ifstream inFile;
infile.open("text.txt");
int counter=0;

if(

while(!infile.eof);

system("pause");
return 0;
}
Hi!

Please use code-tags.

What exactly are you missing?
Use std::string to hold the file then iterate over the chars an check for a white space.
http://www.cplusplus.com/reference/string/string/
http://www.cplusplus.com/reference/string/string/find_first_of/
Welcome to the forum of insane geeks who are completely indescribable.

Checking RedX's links will be of use to you. Also, there's one other thing you will want to know...
http://cplusplus.com/reference/string/getline/

Note the third argument, which I recommend setting to ' '.

-Albatross
The extraction operator (>>) is delimited by whitespace, as well.

You could do something like this:
1
2
3
4
5
6
string word;
while( inFile >> word )
{
    cout << word << endl;
    ++counter;
}

thanks a lot! im gonna work on this and get back to you guys if i have any more problems... sorry, i am new to this... what are code-tags?
http://cplusplus.com/articles/firedraco1/
^Everything you could possibly know about the tags in this forum.

-Albatross

EDIT: Fixed a typo.
Last edited on
Topic archived. No new replies allowed.