In this guide, we will explore input and output redirection along with illustrative instances. Prior to delving into input and output redirection, it is essential to comprehend the concept of redirection in C++.
Changing the default origins or endpoints of input and output streams is known as redirection. This process modifies how a program engages with input and output, offering versatility in managing data from various origins. In the realms of operating systems and programming languages, redirection stands as a crucial concept with multifaceted applications.
Input and output tasks are carried out via streams that represent the flow of data or characters. The standard library offers essential stream entities such as "cin" for receiving input and "cout" for displaying output. These are associated with the keyboard and console, respectively.
I/O redirection entails modifying the standard input and output streams' default sources or destinations without directly interacting with them. This redirection is accomplished by linking stream objects with file streams through the <fstream> library.
Input Redirection:
It is a technique that changes the origin of inputs for a program or command. Rather than retrieving data directly from a default origin such as a keyboard, the input is rerouted to a designated file. For instance, a text analysis program can retrieve input from a file that holds text data instead of requesting input interactively.
Jtp_sample.txt
This is a sample text
Cpp Tutorial is your friend for self-learning
Example:
Let's consider a C++ code example to demonstrate 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 provided code snippet reads words from the file named "jtp_sample.txt", calculates the total number of words in the file, and then increments the wordcount variable accordingly. Following this, the program showcases the final word count on the console screen. Finally, the input file stream is properly closed.
Output redirection:
Output redirection is a technique that alters where a program's output is sent from the standard output device to a designated file. This process is accomplished through the utilization of file stream objects such as "ofstream". It enables the option to append output to pre-existing files, facilitating the accumulation of results across various executions.
Example:
Let's consider a C++ code example to demonstrate 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 program above verifies if the file stream has been opened successfully. Following this, it will show an error message if the file is not found. It proceeds to generate a sequence of numbers from 1 to 10 and then proceeds to write them into the output file with spaces as separators. Finally, it closes the file stream.
Example:
Let's consider a scenario to demonstrate the concept of 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++ software application creates a basic expenditure monitoring system that enables users to input expenses and access a summary. It utilizes file streams ( ofstream and ifstream ) for storing and retrieving expense details from a file named "expenses.txt." The software showcases a user-friendly menu for interacting with users, enabling them to input expenses along with their respective categories and values. Additionally, users can review all recorded expenses and their cumulative total, illustrating fundamental file input/output functionalities in a real-world scenario.