Input and Output in C++


In C++, input and output operations are essential for interacting with the user and external data sources. C++ provides a range of tools and functions to handle input and output, allowing you to read data from the user, display information, and work with files. In this guide, we'll explore the basics of input and output in C++.


Standard Input and Output

C++ uses the iostream library to handle standard input and output. The two primary objects for this purpose are cin and cout:


#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl; return 0;
}

In this example, we use cin to read an integer from the user and cout to display the age.


Formatted Output

C++ allows you to format the output using manipulators and flags. For example, you can control the width and precision of floating-point numbers:


#include <iomanip>
using namespace std;
int main() {
double pi = 3.14159265359;
cout << "Default: " << pi << endl;
cout << fixed << setprecision(2) << "Fixed: " << pi << endl; return 0;
}

In this example, we use setprecision to set the precision of the floating-point number to 2 decimal places.


File Input and Output

C++ allows you to work with files for more advanced input and output operations. You can create, open, read, and write to files using file streams:


#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream outFile("output.txt");
if (outFile.is_open()) {
outFile << "Hello, World!" << endl;
outFile.close();
} else {
cout << "Failed to open the file." << endl;
} ifstream inFile("input.txt");
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "Failed to open the file." << endl;
} return 0;
}

In this example, we use ofstream to write to a file and ifstream to read from a file.


Conclusion

Input and output operations are fundamental in C++ programming, allowing you to interact with users and external data sources. As you continue your C++ journey, you'll explore more advanced I/O techniques and file handling options.