Hello

I am reading a text file & I want to make a for loop, loop repeatedly until the end of the file.

Is my code below correct, in terms of syntax? Is this possible to do.

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;


// function prototypes
void printMenu();

int main()
{
	const int MAX = 250000;
	string words[max];
	int nWord;

	ifstream dict;
	dict.open("dict.txt");
	if (dict.fail())
	{
		cout << "No dictionary file" << endl;
		system("pause");
		return 0;
	}
	// read dictionary into array to make multiple searches faster

	while (dict) {
		for (int i=0; i<dict.eof; i++) { // This is the loop I am referring to :)
			getline(dict,words[i],'\n');
			nWord = i;
		}
	}

	cout << nWord << endl << endl;

	if (nWord > MAX) {
		cout << "Error - Dictionary size of out of bounds";
		system("pause");
		return 0;
	}
for (int i=0; getline(dict,words[i],'\n'); i++) { 
  ..
}

you could use

while(!dict.eof())//this will make it keep going untill the end of line
{
dict.getline(words,sizeof(dict));//this will read line by line 
}

hope it helps

line 14: where is max declared? Note that max is not the same as MAX.

You should use a <vector> instead of string array for two purposes: 1) avoid unnecessary memory allocation, 2) avoid possibility of array overflow (adding too many strings). The <vector> or <list> class will take care of both those problems for you.

you could use

while(!dict.eof())//this will make it keep going untill the end of line
{
dict.getline(words,sizeof(dict));//this will read line by line 
}

hope it helps

Not really -- that loop will cause the last line to be inserted into the array twice.

>>,sizeof(dict)
You mean sizeof(word), assuming word is a character array instead of std::string.

line 14: where is max declared? Note that max is not the same as MAX.

You should use a <vector> instead of string array for two purposes: 1) avoid unnecessary memory allocation, 2) avoid possibility of array overflow (adding too many strings). The <vector> or <list> class will take care of both those problems for you.

I agree, I have just learnt vectors & thats what i would use also. But this is an ssinment & they are making us use an array.

Thx

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.