Reading from Files in C++

Channel:
Subscribers:
2,700
Published on ● Video Link: https://www.youtube.com/watch?v=6nPy5fhafTs



Duration: 1:12:00
202 views
0


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.







Tags:
csci 40
rainfall
c++
fstreams
file i/o
reading from files