Course Content
C++ Tutorial
About Lesson

Input and Output Operations

Input and output operations form the backbone of any program, enabling communication between the program and the external world. In C++, the standard input and output mechanisms provide versatile ways to interact with users and external devices.

Output Streams in C++

Output streams in C++ facilitate the display of data. The cout stream is commonly used to output information to the console. Example:

#include <iostream>
using namespace std;

int main() {
cout << "Hello, World!";
return 0;
}

Formatting Output

C++ offers various manipulators to format output, including setw, setprecision, and left to adjust width, precision, and alignment, respectively. These manipulators ensure a polished presentation of data.

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
double value = 123.45678;
cout << setw(10) << setprecision(4) << left << value;
return 0;
}

Input Streams in C++

The cin stream is used for input operations in C++, allowing users to enter data from the console. Example:

#include <iostream>
using namespace std;

int main() {
int number;
cout << "Enter a number: ";
cin >> number;
cout << "You entered: " << number;
return 0;
}

Handling Input Errors

When receiving user input, it’s essential to handle potential errors. Using functions like cin.fail() or cin.good() helps detect and manage input errors gracefully.

#include <iostream>
using namespace std;

int main() {
int number;
cout << "Enter a number: ";
cin >> number;

if (cin.fail()) {
cout << "Invalid input!";
cin.clear(); // Clearing error flags
cin.ignore(numeric_limits<streamsize>::max(), 'n'); // Clear input buffer
} else {
cout << "You entered: " << number;
}

return 0;
}

File Input and Output

C++ provides file stream classes (ifstream and ofstream) to perform input and output operations on files.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream outputFile("output.txt");
outputFile << "Writing to a file using C++!";
outputFile.close();

ifstream inputFile("output.txt");
string line;
while (getline(inputFile, line)) {
cout << line << endl;
}
inputFile.close();

return 0;
}