I got this problem once but with std::cin. Down below is my program. And the input is:
4
1 4 3 2
5
2 3 4 5 1
1
1
0
The problem was at line 24, the while-loop looped once that means the stringstream had just received the value "2 3 4 5 1".
Let me explain it to you. Here if I replace all the getlines/stringstreams with cin. After the while-loop (at line 9) did everything in it (until line 36), it went back to the 9th line so as to do everything again. Until line 16, n equaled 0 then, after line 16, n should be assigned to any value we entered then, of course but it wasn't. That's the problem. Debug the program and you'll see.