Reading from a file
Lesson 7 of 23 in Coddy's C++ File Handling course.
Reading from a file in C++ can be performed after the file has been opened successfully using an object from the ifstream class.
There are several different ways to read from file:
- Line by Line - you read every line separately throughout the whole file
- Char by Char - you read every character on its own, even including the spaces
- Variable by Variable - you read using ifstream in the same way you would read from standard input, using the
>>operator, so you can read a whole word, a number or even a sign (best for Competitive Programming)
So, now when you know what the different methods of reading from a file are, in the next lessons you can learn how to use them.
There is one important part though, we need to use a loop to keep reading until we reach the end of the file, so there is a special method called .eof() meaning end-of-file, which terminates the loop when the end of the file is reached.
Try it yourself
This lesson doesn't include a code challenge.
All lessons in C++ File Handling
3Reading from Files
Reading from a fileReading Line by LineReading Char by CharReading Variable by VariablePractice Lab #2