-1

I've been struggling with a problem for a while. As I'm reading numbers from a .txt file, the algorithm keeps ignoring the last number from the queue and I don't understand why. How can I rewrite it? I've considered using !f.eof() as well, but I still have doubts. The algorithm should count how many sequences are of even numbers.

input: 1 2 3 4 6 10 2 8 5 7 9 4 6 2 4 8 121 20 4 11 10 2 5 2 6 8 10 16

output: 2

expected output: 3

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

ifstream fin("matrice.txt");

int main()
{
    long a, b, s=0, smax=-1, p;
    fin>>a;
    while(fin>>b)
    {
        if(a%2==0 && b%2==0)
            if(s==0) s+=2;
            else s+=1;
        else
            {
                if(s>smax)
                    { p=1; smax=s;}
                else if(s==smax) p++;
                s=0;
            }
        a=b;
    }
    cout<<p;
    return 0;

}
Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
Lauraa
  • 1
  • 2
  • 4
    *I've considered using !f.eof() as well but I still have doubts.* [Your doubts are well-founded](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). Don't do it. – user4581301 Jun 04 '22 at 16:15
  • Consider running your code in a debugger and stepping through it line by line (though using a breakpoint to skip to the last value in the input file quickly is a pretty good idea, too) and watch what happens. When you see the program do something you didn't expect, like store the wrong value or take the wrong path, you'll have found the bug, and since you watched how the program got there, you might have a few good ideas on how to fix it. – user4581301 Jun 04 '22 at 16:22
  • 4
    Consider this: the code that trips potentially incrementing `p` is based on reading an odd-value. That doesn't happen when your input data *ends* with an even sequence. – WhozCraig Jun 04 '22 at 16:30
  • Heres a pattern: `previous_value = current_value; fin >> current_value;` – Thomas Matthews Jun 04 '22 at 18:12

0 Answers0