counting number of words in a text file in C++

i am kinda of on the right path i think. the problem is i am reading the number of characters in a file but i want to count the number of words in a file and when i do that . i want to use a string and i want to count the number of 5 letter words and the number of 6 or greater words and display them at the end. this is what i got and the output i get is : 1 and thats not right or what i wanted

i dont know if the string deceleration is right to accomplished this

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
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 characters is :" << numb_char << endl;
infile.close();	
return 0;
} 


First check this out: http://www.cplusplus.com/reference/iostream/istream/gcount/


Replace Line 11 with return FALSE;}.

Line 24 might look better like this:
cout << "The number of characters is: " << numb_char << endl;
Notice the white space after the ':' and before the double quotes.

Last edited on
I think the standard string might help you here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <string>
#include <fstream>
#include <iostream>

int main()
{
	std::ifstream ifs("file.txt");
	
	if(!ifs)
	{
		return 1;
	}

	std::string word;
		
	while(ifs >> word)
	{
		std::cout << "word: '" << word << "' has " << word.length() << " characters." << std::endl; 
	}

	return 0;
}
Last edited on
yeah i think gcount or istream& get ( char& c ) or istream& get (char* s, streamsize n ). is what i need to use cuz i want to read the file and then count the number of 5 letter words or less and count the number of 6 or greater words in the file. but i really dont understand how i will put in the program .
Topic archived. No new replies allowed.