File I/O & Robust Programs
So here's the thing — every program you've written so far has a pretty big problem. You run it, you enter all this data, maybe 50 grades into a vector... and then you close the terminal. Poof. Gone. All of it. It's like writing a whole essay on a whiteboard and then someone erases it the moment you walk away. Wouldn't it be nice if your program could actually remember things? That's what this week is all about — making your data persistent by saving it to files on disk, and also learning how to build robust programs that don't just crash when something unexpected happens.
We're going to cover three big skills here. First, file I/O — reading from and writing to files using ofstream and ifstream. And here's the cool part: if you already know cout and cin, you basically already know file I/O. Same << and >> operators, just pointed at a file instead of the screen. Second, we'll get into parsing with stringstream — think of it as a tool that lets you rip apart structured text like CSV data (you know, those comma-separated files) into individual pieces you can actually use. Third, input validation and error handling — because users will type "abc" when you ask for a number, and your program needs to deal with that gracefully using things like cin.fail(), cin.clear(), cin.ignore(), and try/catch.
| Concept | What It Does | Key Class/Function |
|---|---|---|
| Writing files | Saves data to a file on disk | ofstream outFile("data.txt"); |
| Reading files | Loads data from a file on disk | ifstream inFile("data.txt"); |
| Parsing strings | Splits structured text into typed values | stringstream ss(line); |
| Input validation | Detects and recovers from bad user input | cin.fail(), cin.clear(), cin.ignore() |
| Exception handling | Catches and handles runtime errors gracefully | try { ... } catch (exception& e) { ... } |
By the end of this week, your programs will be able to save stuff to files, load it all back, chop up structured text like CSV, and handle errors without blowing up. These are honestly skills you'll use every single day as a programmer — let's get into it.