Problem with input/output with files

I'm really a beginner in C++, so my questions might seem dumb, but still...

I have to write a programm that finds a minimum number in an input file, and counts how many times it appears in the file. The ammount of numbers in the input file is unknown, so I can't use arrays.

1) The first problem is: can I re-read the input file all over again? I use "while (!input.eof())" sequence to find the minimum, and then I try to start over reading the input file by "input.seekg(0)", but it just doesn't work (the value in the variable stays the same as the last number in the file).

2) The second question is: can I use "while (!input.eof())" more than once in the program? Since after using it to finding the minimum it's value is "1" it doesn't work, and I didn't manage to change it in any way I tried.

I'm using Code::Blocks 10.

Here is part of the code, if it helps to understand the problem:
1
2
3
4
5
6
7
8
9
10
11
12
13
    while ( !input.eof() )
    {
        input>>height;
        if (height<min)
         min=height;
    }
    input.seekg (0);
    while ( !input.eof() )
    {
        input>>height;
        if (height==min)
         counter++;
    }
1) Yes
2) Yes

Just put input.clear(); before input.seekg();

1
2
3
4
5
6
7
8
9
10
11
12
13
14
    while ( !input.eof() )
    {
        input>>height;
        if (height<min)
         min=height;
    }
    input.clear(); //  clear 'eofbit' errror flag so you can read from stream again
    input.seekg (0);
    while ( !input.eof() )
    {
        input>>height;
        if (height==min)
         counter++;
    }
Last edited on
Thanks, I'v been trying to find it out in books for like 2 days, and it's so simple...
Topic archived. No new replies allowed.