In Linux the output is printed correctly, with 'lines2' having the same value as 'lines' minus 1, but in windows the value of 'lines2' and is always printed as -2.

The source code is solely for testing purposes, hence the messy code with no for loops, bad variable names etc.

Apologies for posting about something fundamental as this (and posting a messy source code).

Any help is very much appreciated.

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

main()
{
ifstream fis;
string str = "";
string filename;
int lines= -1;
int lines2 = -2;
cout << "Enter file: " << endl;
cin >> filename;

fis.open(filename.c_str());

while(!fis.eof())
    {
	lines++;
	fis >> str;
    }
fis.close();

cout << "Lines:" << lines;

fis.open(filename.c_str());

while(!fis.eof())
    {
	lines2++;
	fis >> str;
    }
fis.close();

cout << "Lines-1:" << lines2;
return 0;
}

After you close the file for the first time, the eofbit is still set. You need to clear it with fis.clear(); before the second loop will work. Apparently your Linux compiler chose to clear the state either on close or open.

while(!fis.eof())
    {
	lines2++;
	fis >> str;
    }

two problemss:
1) that counts the number of words, not lines. If you really want lines then call getline()

2) That will count the last line/word twice because eof() doesn't work lilke that. Here's how to code the loop

while( fis >> str)
   ++lines2;

Thank you both, problems solved etc.

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.