answersLogoWhite

0


Best Answer

Redirection applies to the standard input/output devices. Although it is up to the user to decide which device provides input and which provides output for your program, the programmer can choose to redirect those devices as they see fit. However, it is important that the programmer restore the original devices as soon as they have finished with them.

The following example demonstrates one way of redirecting the standard input/output devices programmatically:

#include <iostream>

#include <fstream>

#include <string>

void f()

{

std::string line;

while (std::getline(std::cin, line)) // input from stdin

{

std::cout << line << "\n"; //output to stdout

}

}

int main()

{

std::ifstream in("in.txt");

std::streambuf *cinbuf = std::cin.rdbuf(); // save old buf

std::cin.rdbuf(in.rdbuf()); // redirect std::cin to in.txt!

std::ofstream out("out.txt");

std::streambuf *coutbuf = std::cout.rdbuf(); // save old buf std::cout.rdbuf(out.rdbuf()); // redirect std::cout to out.txt!

std::string word;

std::cin >> word; // input from the file in.txt

std::cout << word << " "; // output to the file out.txt

f(); // call function

std::cin.rdbuf(cinbuf); // reset to standard input again

std::cout.rdbuf(coutbuf); // reset to standard output again

std::cin >> word; // input from the standard input

std::cout << word; // output to the standard input

}

User Avatar

Wiki User

9y ago
This answer is:
User Avatar
More answers
User Avatar

Wiki User

11y ago

Redirection means to change the console input and/or output streams. stdin and stdout normally refer to the keyboard and screen, but the caller can redirect either or both of these calls to a file stream specified on the command line. Objects that are extracted from stdin (>>) or inserted to stdout (<<) will be redirected to the appropriate streams accordingly.

This answer is:
User Avatar

Add your answer:

Earn +20 pts
Q: What is mean by redirection in c plus plus?
Write your answer...
Submit
Still have questions?
magnify glass
imp