Open In App

How to Redirect cin and cout to Files in C++?

Last Updated : 30 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to redirect cin and cout to files
#include <fstream>
#include <iostream>
  
using namespace std;
  
int main()
{
    // Opening the input file stream and associate it with
    // "input.txt"
    ifstream fileIn("input.txt");
  
    // Redirecting cin to read from "input.txt"
    cin.rdbuf(fileIn.rdbuf());
  
    // Opening the output file stream and associate it with
    // "output.txt"
    ofstream fileOut("output.txt");
  
    // Redirecting cout to write to "output.txt"
    cout.rdbuf(fileOut.rdbuf());
  
    // Variables for input
    int x, y;
    // Reading two integers from "input.txt"
    cin >> x >> y;
    // Writing the product of the two integers to
    // "output.txt"
    cout << "Product: " << (x * y) << endl;
  
    return 0;
}


input.txt

10 20

output.txt

200

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads