Reading from Files in C++
Today we learned the fstreams interface to read from files. It works basically just like reading from the keyboard (with cin) except you need an extra step to create a new variable linked to the file to read from -
ifstream bob("mencarelli.txt"); //This creates a variable named bob that will read from mencarelli.txt
Then any line we have where we read from cin we could read from bob instead, and instead of the characters coming from the keyboard, they will come from the file as if they were typed in.
So, it's pretty easy, but there are two extra checks we have to do when working with files:
1) Check to see if the file failed to open with: if (!bob)
2) Every time we do a read we need to see if an error occured from reading off the end of the file: if (!bob)
So yeah, if you're used to doing an if (!cin) a lot, then you'll be fine with this.
We finished by doing the Rainfall assignment in lab time. It's a famous computer science assignment.
Other Videos By Bill Kerney
2021-10-07 | Dijkstra Part II + Minimal Spanning Trees |
2021-10-07 | Making a 3D Engine in a Terminal |
2021-10-06 | Fallacies |
2021-10-06 | Pointers and Mapping 2D Arrays to 1D Arrays |
2021-10-06 | Graph Traversal + Dijkstra's Algorithm |
2021-10-06 | The Infamous Kitty Rocket Launcher |
2021-10-06 | Swimming, Delta Time, Terminator Barrel, UMG HUDs |
2021-10-04 | ACM Talk: Hazelton Teaches Vim |
2021-10-04 | Writing to Files, Error Messages in C++ (scary), and Recursion |
2021-10-04 | Midterm Review + Equivocation Fallacy |
2021-10-02 | Reading from Files in C++ |
2021-10-02 | Fallacies Part I |
2021-09-30 | How to export and import assets between projects in UE4 |
2021-09-30 | Making an AI Enemy Part II |
2021-09-30 | Invalid/Valid/Sound II + Hamiltonian/Eulerian Paths and Cycles |
2021-09-30 | UE4 Damage System and HUDs with UMG |
2021-09-30 | Top-Down and Bottom-Up Programming |
2021-09-29 | Midterm I Review |
2021-09-29 | Making a Castle with the Procedural Spline Walls System |
2021-09-28 | Making an AI Opponent Part I |
2021-09-28 | Graph Theory I |