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

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



Reffered: https://www.geeksforgeeks.org


C++

Related
How to use errno in C++? How to use errno in C++?
How to Merge Multiple std::sets into a Single std::set in C++? How to Merge Multiple std::sets into a Single std::set in C++?
How Can I Get All the Unique Keys in a Multimap? How Can I Get All the Unique Keys in a Multimap?
How to Set, Clear, and Toggle a Single Bit in C++? How to Set, Clear, and Toggle a Single Bit in C++?
Overloading Relational Operators in C++ Overloading Relational Operators in C++

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13