This is very useful for OJ on the topic. OJ is basically the standard input output (except for Usaco). But if you're typing from the console while you're debugging, it's a waste of precious time. We can redirect the standard input, debug the time from the file to read, commit to read from the standard input.
In the C language, the method is relatively simple. Use function Freopen ():
- Freopen ("data.in","R", stdin);
- Freopen ("Data.out","W", stdout);
This redirects the standard input to the data.in file, and the standard output is redirected to the Data.out file.
After these two lines of code, the SCANF function is read from the data.in file, and the printf function is output to the Data.out file.
In C + +, there are two overloaded functions for convection redirection:
- streambuf* rdbuf () const;
- streambuf* rdbuf (STREAMBUF *)
is equivalent to the Get/set method.
- Streambuf *backup;
- Ifstream fin;
- Fin.open ("data.in");
- Backup = Cin.rdbuf (); //Back up CIN ' s streambuf
- Cin.rdbuf (Fin.rdbuf ()); //Assign file ' s streambuf to CIN
- ... cin would read from file
- Cin.rdbuf (Backup); //Restore CIN ' s original Streambuf
Note that in the end we used Cin.rdbuf (backup) to redirect Cin back to the console.
However, it is less elegant to implement the same functionality in C.
Because the name of the standard console device file is associated with the operating system.
In Dos/windows, the name is con.
Freopen ("Con", "R", stdin);
In Linux, the console device is/dev/console
Freopen ("/dev/console", "R", stdin);
In addition, in Unix-like systems, the DUP system can also be used to pre-replicate a copy of the original stdin handle.
C + + Standard IO redirection