im trying to figure out how i count the number of 5 letter words in a file and the number of 6 or greater words in the same file using a string. all the examples are at higher level of programming im just a beginner. my books very briefly tells me how to count characters and not words. but from that i got this and my output just says the number of words is: 1. could i get the basic syntax on how to count words in a text file in c++

ifstream infile;
//char mystring[6];
//char mystring[20];

int main()
{
	infile.open("file.txt");
		if(infile.fail())
		{
			cout << " Error " << endl;
		}
	
	int numb_char=0;
	char letter;
		
		while(!infile.eof())
			{
			infile.get(letter);
			cout << letter;
			numb_char++;
				
			}
	
cout << " the number of words is :" << numb_char << endl;
infile.close();	
return 0;

Edited 6 Years Ago by timbomo: n/a

Your going to want to set up a loop to read through the entire string(Your sentence). As at loops through one char at a time, you add to a counter variable if you encounter a space char(' ').

So in your while loop there, set up an if statement. So, if the char is ' ', then increment you numb_char variable.

while(!infile.eof())
{
    infile.get(letter)

    if(letter == ' ')
    {
        numb_char++;
    }
}

You probably want to rename your numb_char variable to something more suiting, like numb_words. Just for fun =)

Edited 6 Years Ago by LevyDee: n/a

the output is not 1 anymore its 0 so i am moving in the right direction. im lookin up gcount and it seems like that might be an function that i can use but it doesnt show how 2 use it. is that it ?

Well, you could easily count the spaces, and do -1 on the final number (last space is actually not before a word...)any if you know how to count chars, you sure could count spaces

This article has been dead for over six months. Start a new discussion instead.