0

I have a simple program where I am trying to redirect a file to stdin and print out each line. I know each line has two numbers but I don't know how many lines there are.

#include <bits/stdc++.h>
using namespace std;

int main()
{
    ifstream in("input.txt");
    cin.rdbuf(in.rdbuf()); // redirect to stdin

    while(!cin.eof())
    {
        int a, b;
        std::cin >> a >> b;
        std::cout << "a = " << a << ", b = " << b << std::endl;
    }

    return 0;
}

If I run this on "input.txt"

1 2
3 4

I get the output

a = 1, b = 2
a = 3, b = 4
a = 3, b = 4

Why is the second line being read twice by cin?

Paradox
  • 1,809
  • 13
  • 24
  • 1
    your code should be `while( cin >> a >> b )...` see duplicate for explanation – Slava Jun 02 '20 at 22:52
  • delete the trailing \n at the end of the file, editor add it always, remove it and everything works fine – Berto99 Jun 02 '20 at 22:52
  • 1
    @Berto99 you have strange opinion on "works fine". It should work fine unrelated to trailing \n in the file (even if that is the case here) – Slava Jun 02 '20 at 22:54
  • @Slava sorry "will work fine for your input, but not in all cases" – Berto99 Jun 02 '20 at 22:55

0 Answers0