freopen
also works with cin
and cout
. No need to search for something new.
freopen("input.txt", "r", stdin); // redirects standard input
freopen("output.txt", "w", stdout); // redirects standard output
int x;
cin >> x; // reads from input.txt
cout << x << endl; // writes to output.txt
Edit: From C++ standard 27.3.1:
The object cin controls input from a stream buffer associated with the object stdin, declared in <cstdio>
.
So according to the standard, if we redirect stdin
it will also redirect cin
. Vice versa for cout
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…