The assignment my instructor has assigned as for to read an input file and count all 3, 4, 5, and 6 letter words and out put those to an output file. From what data I had been provided by my instructor, I think he wants us to use char data for the letters/words. I the code below is as far as I have gotten. The result I get is just punctuation.

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


using namespace std;

int main()
{

	ifstream FileIn;
	ofstream FileOut;
	
	FileIn.open ("m:\\QUOTES.txt");
	FileOut.open ("m:\\NUMWORDS.txt");

	char charin;
	int count = 0;
	int count3 = 0;
	int count4 = 0;
	int count5 = 0;
	int count6 = 0;

	while ( FileIn )
 {
		FileIn.get ( charin );
		count = 0;

	while ( charin >= 'A' && charin <= 'Z' || charin >= 'a' && charin <= 'z' )
	{
		
		count++;
		FileIn.get ( charin );
	}
	
		if   ( count == 3 )
			 count3++;
		else if( count == 4)
			 count4++;
		if   (count == 5)
			count5++;
		else if( count == 6 )
			count6++;
		{
	}

	FileOut << charin;
 }


	


return 0;
}

Recommended Answers

All 3 Replies

Read the file a word at a time instead of a character at a time.

std::string word
while( FileIn >> word )
{
   // blabla
}

Then if the word is 3-6 characters add it to a list with a counter for the number of times that word appeared in the file. There are a couple of ways to do it -- one way is to use <map>, that that may be more than you know how to do at the present time. The other way us to use an array of structures.

struct words
{
    std::string word;
    int count;
};

Well, there is a third alternative and that is to use two arrays, one string and the other count

std::string words[255];
int count[255] = {0};

However you decide to do it you will have to search the array to see if the word just read is already in the array. If it is, just increment the count for that word. If not then add the word to the array.

When all that is done then you are ready to write all those words and their respective counts to the output data file.

I guess I don't get the way my instructor is wanting it, cant really ask him this week, since its spring break, we are not into arrays or anything beyond while and do loops. The way he was explaining things was he was using char data to find the letters. Most of the code I have is info he gave.

If you can't use std::string then you can use char. I thought you had to count the words too, but maybe not so I may have made your program more complicated than it needs to be.

Read a word, call strlen() to find out how long the word is. If the word is between 3 and 6 characters then write it out to an output file.

char word[8]; // assumes words are no larger than 8 characters
while( FileIn >> word )
{
   // blabla
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.