what AmI missing? I am simply trying to read in an array from a txt file and count the words. What am I doing wrong....here is the function

int countwords(ifstream& infile, int wordcount[MAX_WORDS])
{
	int count = 0;
	
	for( int i=0; i < MAX_WORDS && infile; i++)
	{
		infile>>wordcount[i];
		count++;
	} 
	return count;
}

maybe this will work for you. It doesn't need two counters -- only one is sufficient. If you are trying to read words then why is wordcount an int array instead of std::string array?

int countwords(ifstream& infile, int wordcount[MAX_WORDS])
{
	int count = 0;
	
	while(  count < MAX_WORDS && infile>>wordcount[count])
	{
		count++;
	} 
	return count;
}

Edited 6 Years Ago by Ancient Dragon: n/a

full code is as follows

//Hangman in C++
//Patrick Nealey

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

const int MAX_WORDS = 100;

using namespace std;

bool LoadFile(ifstream& infile, string words[MAX_WORDS]);
int countwords(ifstream& infile, int wordcount[MAX_WORDS]);

int main()
{
	string words[MAX_WORDS];
	int wordcount[MAX_WORDS];
			
	cout <<"Welcome to Hangman...Don't lose your head!"<<endl;

	ifstream infile ("words.txt");
	if(!infile)
	{
		cerr <<"Could not open input file";
		return -1;
	}

	LoadFile(infile, words);
	cout <<"# of words = "<<countwords(infile, wordcount);
		
	return 0;
}
bool LoadFile(ifstream& infile, string words[MAX_WORDS])
{
	for (int i = 0; i < MAX_WORDS; i++)
	{
		if (!infile)
		{
			return false;
		}
		infile >> words[i];
		cout << words[i]<<endl;
	}	
	return true;

}
 int countwords(ifstream& infile, int wordcount[MAX_WORDS])
{
   int count = 0;
   
   while( count < MAX_WORDS && infile>>wordcount[MAX_WORDS])
   {
	   count++;
   }
   return count;
}

this is just the beginning of a much larger program, but i cannot continue until i figure out the count

you still have not told us why wordcount is an array of integers.

The function returns 0 because the file stream is already at end-of-file. There's nothing more to read. LoadFile() has already read the whole file, so countWords() has nothing to do.

Suggestion to fix:
(1) delete wordcount array because it is of no value.
(2) delete countword() function because it has nothing to do.
(3) change LoadFile() to return the count of the words read instead of just true or false. It already knows the count -- variable i. So just return its value.
(4) Change the while loop in LoadFile() so that it is similar to the new one you put in countwords().

Edited 6 Years Ago by Ancient Dragon: n/a

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