Writing to Files, Error Messages in C++ (scary), and Recursion

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



Duration: 1:02:31
179 views
2


Note: a secret effect of the -fcompare-debug-second flag is to disable all notes on compilation, but the fact remains that it is idiotic that there is no flag to turn off template substitution errors if you don't want to see them.


Writing to files in C++ is really easy with the fstreams header. Like with reading from files, you just need one extra line of code to connect the file with a variable that you can write to, as such:
ofstream outs("hazelton.txt");


ofstream is the type, which is an output file stream, the name of the variable is outs, the file it will write to is hazelton.txt. NOTE: WHEN YOU DO THIS THE FILE hazelton.txt IS ERASED. (There is append mode, but truncate mode is the default.)


You can then write data to outs like you write to cout, and everything works as expected.


We then talked about the worst part of C++, which is the compiler error messages. In particular, there is a certain class of compiler error messages that spam the user with page after page of useless information - and unlike literally everything else I can think of when it comes to warnings and errors, g++ has no flag to disable them.


The key to dealing with lots of errors is to look only at the top one and fix that, and ignore the rest. If you pipe your output into less, it will show one page of errors at a time:


g++ main.cc |& less


Third, we talked about recursion. Recursion is when a function calls itself. It is like writing a loop, but without a loop. You need two things to make recursion work: 1) A base condition that ends the infinite regress, and 2) to ensure that the program will always move towards the base condition.


Recursion allows some beautiful code to be written cleanly and simply when problems exhibit the "self-similarity" property, like with a fractal, when the small scale problem resembles the large scale problem, like the Fibonacci Sequence, which is defined in terms of itself.







Tags:
csci 40
c++ error messages
ofstream
writing to files
C++
recursion