In C++, streams represent the flow of data in sequence. There are two main types of I/O operations:
cin
: Associated with keyboard (input)cout
: Associated with monitor (output)cerr
: Error streamclog
: Logger streamC++ provides three main classes for file operations:
#include <fstream>
#include <iostream>
using namespace std;
int main() {
// Writing to a file
ofstream outFile("data.txt");
if(outFile.is_open()) {
outFile << "Hello, this is sample text." << endl;
outFile << 100 << " " << 3.14 << endl;
outFile.close();
}
// Reading from a file
ifstream inFile("data.txt");
if(inFile.is_open()) {
string line;
while(getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
}
return 0;
}
ios_base::out
: Write mode (creates new file or truncates existing)