Word count from input file problem

Hello, I'm a C++ student trying to finish an assignment. My level of knowledge is pretty basic. The assignment requires the program to count the amount of words in an input file. My logic was to have it count the amount of spaces and then adding one more in order to know the total amount of words in the file. I was able to open the file and count the total amount of characters but I'm stuck on the part where it should count a specific character, in this case the space character. My teacher recommended this website. If someone could at least point me in the right directions as to what I'm doing wrong. I would really appreciate any help. Thank you.

int main ()
{
cout<<"This program will search for a word in file and provide the user with ";
cout<<"the amount of times it appeared and the percentage occurrence compared with other ";
cout<<"words in the file.\n";


ifstream in;
string InputFile;
cout<<"Enter the full path the input file: ";
getline(cin,InputFile);
cin.sync();

in.open(InputFile.c_str());

if(in)
{
cout<<"File opened successfully.\n";
int counter = 0;
char Spaces;

while(in)
{
in>>Spaces;//retrieve the characters

while(isspace(Spaces))//Testing for the space character
{
counter ++;
}

}
cout<<"The amount of words in the file is "<<counter<<".\n";
}
else
{
cout<<"File did not open.\n";
}
return 0;
}[/code]
You want to loop while:
(!in.eof()) <- have not reached the end of "in" file

Here's a tutorial on getline:
http://www.cplusplus.com/reference/iostream/istream/getline/

also, I would say in = Spaces.get... I don't know if there's a real difference, but I prefer that method
(in other words you don't have to change for it to work =)

oh and you may wish to reevaluate your if(in) check.

edit: oh and you don't need a while loop for your isspace function.

(this is just first glance, not comprehensive)
Last edited on
here's how i would do it

1
2
3
4
5
6
int counter = 0;
string whatever;

while (in >> whatever) {
    counter++;
}


counting the spaces should work also. there's a couple good ways to do it that i can think of

if (someChar == 32) //check you ASCII table, but i think that's right

if (isSpace(someChar))

your loop would count consecutive spaces, which probably wouldn't be an issue, but your logic would fail if there were multiple spaces between words and your count would be wrong

also, doing it your way, you want to use Spaces = in.get(); instead of in >> Spaces;

hope this helps
Last edited on
counting just the spaces might not be enough. There can be a case where two spaces separate a word, etc.
See the below link
http://www.java-forums.org/new-java/39832-counting-words.html#post183418

I have replied to a same issue in Java forum (post #6) recently. A copy paste wont work. But see the logic and translate it to c++.
Topic archived. No new replies allowed.