The Standard Library Lesson 16 of 17
C++ File Streams and Exceptions
Read and write files with ofstream, ifstream and getline, parse CSV lines with stringstream, and handle errors with try, catch, throw and standard exceptions.
C++ reads and writes files with the same << and >> operators you use for cout and cin. And when something goes wrong, exceptions let you handle the error in one clear place.
Writing a file: ofstream
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out("grades.txt");
if (!out) {
cerr << "Could not open file" << endl;
return 1;
}
out << "Ana 91\n";
out << "Ben 84\n";
out << "Carla 95\n";
out.close();
cout << "Saved." << endl;
return 0;
}
Output
Saved.
ofstream (output file stream) creates or overwrites the file. To add to the end instead, open it with ofstream out("grades.txt", ios::app);. The file also closes automatically when out goes out of scope.
Reading a file: ifstream
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ofstream("grades.txt") << "Ana 91\nBen 84\nCarla 95\n"; // create a sample file
ifstream in("grades.txt");
if (!in) {
cerr << "File not found" << endl;
return 1;
}
string name;
int grade, sum = 0, count = 0;
while (in >> name >> grade) {
cout << name << ": " << grade << endl;
sum += grade;
count++;
}
cout << "Average: " << static_cast<double>(sum) / count << endl;
return 0;
}
Output
Ana: 91 Ben: 84 Carla: 95 Average: 90
while (in >> name >> grade) keeps reading until the end of the file or bad data.
Reading lines and CSV with stringstream
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ofstream("sales.csv") << "Pandesal,10,2.50\nKape 3-in-1,4,8.00\nItlog,6,9.00\n";
ifstream in("sales.csv");
string line;
double total = 0;
while (getline(in, line)) {
stringstream ss(line);
string item, qtyText, priceText;
getline(ss, item, ',');
getline(ss, qtyText, ',');
getline(ss, priceText, ',');
double amount = stoi(qtyText) * stod(priceText);
cout << item << ": " << amount << endl;
total += amount;
}
cout << "Total: " << total << endl;
return 0;
}
Output
Pandesal: 25 Kape 3-in-1: 32 Itlog: 54 Total: 111
getline(in, line) reads a whole line, even with spaces. A stringstream then lets you split that line with getline(ss, part, ',').
Exceptions: try, catch, throw
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;
double divideBill(double total, int people) {
if (people <= 0) throw invalid_argument("people must be at least 1");
return total / people;
}
int main() {
try {
cout << divideBill(900, 3) << endl;
cout << divideBill(900, 0) << endl;
cout << "This line is skipped" << endl;
} catch (const invalid_argument &e) {
cout << "Error: " << e.what() << endl;
}
cout << "Program continues." << endl;
return 0;
}
Output
300 Error: people must be at least 1 Program continues.
throwraises an exception and leaves the current function immediately.trymarks code that might throw;catchhandles a specific type.e.what()returns the error message.- Catch by
const &to avoid copying the exception object.
Standard exceptions you'll meet
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;
int main() {
vector<int> v = {1, 2, 3};
try {
cout << v.at(10) << endl;
} catch (const out_of_range &e) {
cout << "out_of_range caught" << endl;
}
try {
int n = stoi("sampu");
cout << n << endl;
} catch (const invalid_argument &e) {
cout << "invalid_argument caught" << endl;
}
try {
throw runtime_error("printer offline");
} catch (const exception &e) { // catches any standard exception
cout << "exception: " << e.what() << endl;
}
return 0;
}
Output
out_of_range caught invalid_argument caught exception: printer offline
All standard exceptions inherit from std::exception, so catch (const exception &e) catches any of them. Put specific catch blocks before general ones.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04