The fstream library allows us to work with files.
To use the fstream library, include both the standard
There are three classes included in the fstream library, which are used to create, write or read files
Class
Description
ofstream
creates and writes to files
ifstream
reads from files
fstream
creates, writes and reads files
Create and Write To a File
To create a file, use either the ofstream or fstream class, and specify the name of the file.
To write to the file, use the insertion operator (<<).
Why do we close the file?
It is considered good practice, and it can clean up unnecessary memory space.
Read from a File
To read from a file, use either the ifstream or fstream class, and the name of the file.
Note that we also use a while loop together with the getline() function
(which belongs to the ifstream class) to read the file line by line,
and to print the content of the file
Exceptions:-
When executing C++ code, different errors can occur:
coding errors made by the programmer, errors due to wrong input,
or other unforeseeable things.
When an error occurs, C++ will normally stop and generate an error message.
The technical term for this is: C++ will throw an exception (throw an error).
C++ try and catch
Exception handling in C++ consist of three keywords: try, throw and catch:
The try statement allows you to define a block of code to be tested for errors while it is being executed.
The throw keyword throws an exception when a problem is detected, which lets us create a custom error.
The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
The try and catch keywords come in pairs
We use the try block to test some code:
If the age variable is less than 18,
we will throw an exception, and handle it in our catch block.
In the catch block, we catch the error and do something about it.
The catch statement takes a parameter: in our example we use an int variable (myNum)
(because we are throwing an exception of int type in the try block (age)),
to output the value of age.
If you do not know the throw type used in the try block, you can use the "three dots" syntax (...) inside the catch block, which will handle any type of exception