How to Redirect cin and cout to Files in C++?
Last Updated :
30 Jan, 2024
In C++, we often ask for user input and read that input using the cin command and for displaying output on the screen we use the cout command. But we can also redirect the input and output of the cin and cout to the file stream of our choice.
In this article, we will look at how to redirect the cin and cout to files in C++.
Redirecting cin and cout to a File in C++
For redirecting cin and cout to a file, we first create the input file stream and output file stream to our desired file. Then using rdbuf() function of stream objects, we redirect the input for cin to the file and output for cout to the file.
C++ Program to Redirect cin and cout to a File
C++
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ifstream fileIn( "input.txt" );
cin.rdbuf(fileIn.rdbuf());
ofstream fileOut( "output.txt" );
cout.rdbuf(fileOut.rdbuf());
int x, y;
cin >> x >> y;
cout << "Product: " << (x * y) << endl;
return 0;
}
|
input.txt
10 20
output.txt
200
Share your thoughts in the comments
Please Login to comment...