counting numbers in a text file

Hi guys,

I have a simple problem. There is a text file with floating point numbers in it, separated by '\t' or '\n', and I want to count them. Sounds easy, but unfortunately not for me.

Here is the code I'm using:
1
2
3
4
5
6
7
8
9
10
int nElements=0;
std::ifstream inputData; 
inputData.open("inputfile.txt");
while (inputData.good())
{
    float i;
    inputData >> i;
    nElements++;
}
inputData.close(); 


Here is an example of an input file:
702.24^I702.23^I702.22^I702.21^I702.2^I702.19$
699.45^I699.44^I699.43^I699.42^I699.41^I699.4$


The problem is, there is sometimes a carriage return at the end of the file, and sometimes not. If there is one, my code returns me n+1 instead of n as nElements.

Does anyone have an idea, how can I cope with it?

Best regards!
The proble is that you increase nElements even if inputData >> i results in an error (like eof).

You can easily write it like so:
1
2
3
4
5
float i;
while (inputData >> i) // This checks whether it's good or not
{
    nElements++;
}
Thanks a lot, it works!

I thought, inputData.good() checks, if there would be a problem. But, obviously I was wrong.
Last edited on
I thought, inputData.good() checks, if there would be a problem. But, obviously I was wrong.
It checks, but the damage is already done (ie nElements++) when it checks
Topic archived. No new replies allowed.