C++ handles input and output through streams, which are sequences of bytes transferred between the program and devices (e.g., console, files). Key subtopics include:
cin (input) and cout (output) from the <iostream> library, managing data as a continuous flow.<iostream> library defines a hierarchy of classes:
ios (base class for stream state and formatting).istream (input operations, e.g., cin).ostream (output operations, e.g., cout).iostream (combines input and output, inherits from istream and ostream).fail(), eof(), and good() to check for errors (e.g., invalid input, end-of-file).This program demonstrates console I/O with error checking for invalid input.
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
// Test for input errors
if (cin.fail()) {
cout << "Error: Invalid input. Please enter a number." << endl;
cin.clear(); // Clear error state
cin.ignore(10000, '\\n'); // Discard invalid input
} else {
cout << "You entered: " << age << endl;
}
// Check stream state
if (cin.good()) {
cout << "Stream is in a good state." << endl;
}
return 0;
}
Explanation:
Stream-based I/O: Uses cin for input and cout for output.
Error Testing: cin.fail() checks for invalid input (e.g., entering a string instead of an integer).
Stream State: cin.clear() and cin.ignore() handle errors; cin.good() confirms stream health.
Sample Output (valid input: 25):
Enter your age: 25
You entered: 25
Stream is in a good state.
Sample Output (invalid input: abc):
Enter your age: abc
Error: Invalid input. Please enter a number.
Unformatted I/O involves reading or writing raw data without specific formatting. Functions include:
get() and getline() for input (reading characters or lines).