In this article, we will discuss input and output redirection with their examples. But before discussing input and output redirection, we must know about the redirection in C++.
Redirection refers to changing the default sources or destinations of input and output streams. It alters the way a program interacts with input and output. It is a fundamental concept in operating systems and programming languages, and it is used for many purposes. It provides flexibility in handling data from different sources.
Input and output operations are performed through streams representing the sequence of data or characters. The standard library provides fundamental stream objects like "cin" for input and "cout" for output. These are related to the keyboard and console, respectively.
I/O redirection involves changing the default sources or destinations of input and output streams instead of interacting with the standard input and output. This redirection is achieved by associating the stream objects with file streams using the <fstream> library.
Input Redirection:
It is a concept that alters the source of inputs for a program or command. Instead of reading information directly from a default source like a keyboard, the input is redirected to a specific file. For example, a program designed to analyze text can read input from a file containing text data rather than prompting for input.
Jtp_sample.txt
This is a sample text
Cpp Tutorial is your friend for self-learning
Example:
Let us take a C++ program to illustrate the input redirection :
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream inputFile("jtp_sample.txt");
if (!inputFile) {
cerr << "Error opening file!\n";
return 1;
}
int wordCount = 0;
string word;
while (inputFile >> word) {
wordCount++;
}
cout << "Total words in the file: " << wordCount << endl;
inputFile.close();
return 0;
}
Output:
Explanation:
The above program will read words from the "jtp_sample.txt" file, count the number of words in the file, and increment the wordcount variable. After that, this program displays the total word count on the console. After that, the input file stream is closed.
Output redirection:
Output redirection is a concept that changes the destination of a program's output from the default output device to a specific file. It is achieved using file stream objects like "ofstream" . Output redirection will support appending to existing files, making it possible to accumulate results over multiple runs.
Example:
Let us take a C++ program to illustrate the output redirection :
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outputFile("jtp_sample.txt");
if (!outputFile) {
cerr << "Error opening file for writing!\n";
return 1;
}
for (int i = 1; i <= 10; ++i) {
outputFile << i << " ";
}
cout << "Numbers generated and written to jtp_sample.txt\n";
outputFile.close();
return 0;
}
Output:
Explanation:
The above program will check whether the file stream is successfully opened. After that, it displays an error message if the file is not present. The program generates the numbers from 1 to 10 and then writes them in the output file separated by spaces to the output files. After that, the file stream is closed.
Example:
Let us take an example to illustrate the Input and Output redirection in C++.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <sstream>
using namespace std;
void displayMenu() {
cout << "Expense Tracker Menu:\n";
cout << "1. Add Expense\n";
cout << "2. View Expenses\n";
cout << "3. Exit\n";
}
void addExpense(ofstream& outputFile) {
string category;
double amount;
cout << "Enter expense category: ";
cin.ignore();
getline(cin, category);
cout << "Enter expense amount: ";
cin >> amount;
outputFile << category << "," << amount << endl;
cout << "Expense added successfully!\n";
}
void viewExpenses(ifstream& inputFile) {
string line;
double totalExpenses = 0.0;
cout << setw(20) << left << "Category" << setw(10) << right << "Amount\n";
cout << setfill('-') << setw(30) << "" << setfill(' ') << endl;
while (getline(inputFile, line)) {
string category;
double amount;
istringstream iss(line);
getline(iss, category, ',');
iss >> amount;
cout << setw(20) << left << category << setw(10) << right << amount << endl;
totalExpenses += amount;
}
cout << setfill('-') << setw(30) << "" << setfill(' ') << endl;
cout << "Total Expenses: " << totalExpenses << endl;
}
int main() {
ofstream outputFile("expenses.txt", ios::app);
ifstream inputFile("expenses.txt");
if (!outputFile || !inputFile) {
cerr << "Error opening file!\n";
return 1;
}
int choice;
do {
displayMenu();
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
addExpense(outputFile);
break;
case 2:
viewExpenses(inputFile);
break;
case 3:
cout << "Exiting Expense Tracker. Have a nice day!\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 3);
outputFile.close();
inputFile.close();
return 0;
}
Output:
Explanation:
This C++ program implements a simple expense tracker with options to add expenses and view a summary. It uses file streams ( ofstream and ifstream ) to write and read expense data to/from a file named "expenses.txt." . The program displays a menu for user interaction, allowing the addition of expenses with categories and amounts. It also allows viewing all expenses and their total, demonstrating basic file I/O operations for a practical application.