.eof problem in file handling in Turbo C++

Jan 15, 2016 at 10:16pm
I'm trying to write a code that counts the number of words and lines in a file, but it only outputs the number of words and not the number of lines. Whenever I trace the code, it does not execute the while loop for the word. I'm just a beginner, please, come someone assist me?

I've already made a code.

P.S. we are really required to use the Turbo C++ compiler

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  void countWord(ifstream& ifile, char wordText[100][100], int a, int ctr)
{
	while(!ifile.eof())
	{
		ifile >> wordText[a];
		a++;
		ctr++;
	}
	cout << "Number of words in file: " << ctr << endl;
	getch();
}

void countLine(ifstream& ifile, char lineText[], int size)
{
	int a;
	int g = 0;

	while(ifile.getline(lineText, size, '.'))
	{
		g++;  
	}
	cout << "Number of lines in file: " << g <<endl;
}

void main()
{

	clrscr();
	ifstream ifile;
	ofstream ofile;
	int a = 0;
	int inc = 0;
	char lineText[100];
	char storeText[100][100];
	ifile.open("texts.txt");
	ofile.open("ans.txt");

	/*while(!ifile.eof())
	{
		ifile >> storeText[a];
		a++;
		inc++;
	}*/

       /*while(ifile.getline(lineText, 100, '.'))
	{
		g++;

	}*/
	countWord ( ifile, storeText, a, inc);
	countLine ( ifile, lineText, 100);

	//cout << "Number of words in the file is: " << inc << endl;
	//cout << "Number of lines is: " << g << endl;
	getch();
	system("pause");
}
Jan 15, 2016 at 11:39pm
You mean you already wrote some code. Code is plural.

When you trace into the countWord() function, what happens? Please post exactly what you see.
Jan 16, 2016 at 12:01am
It always outputs
Number of words in the file is: 11 (Which is correct) so countWord() function may be correct
but in the countLine() function, it doesn't execute the while loop therefore it alway displays
Number of lines is: 0
Jan 16, 2016 at 12:36am
You feed countLine a stream that is already at the end of file.
Last edited on Jan 16, 2016 at 12:37am
Jan 16, 2016 at 12:40am
Cire (as always) is correct. You need to review the ifstream section.
Topic archived. No new replies allowed.