In this module we discuss input and output!
What makes our computers useful machines is the ability to input information, and retrieve the output of a computers computation. A simple example of input and output would be to use a calculator to compute the result of some arithmetic computation and compute a result for us humans. So one could argue that input and output is quite fundamental to what computers do!
Now there are many types of input and output that we might classify into different categories. For example:
I think the most common form that we think of is with text processing. For example, we have looked at how to write out text to the terminal.
// SimpleOutput.cpp
#include <iostream>
int main(){
std::cout << "Hello my programming friends!" << std::endl;
return 0;
}
Note: With C++ 23 we have functionality for std::print. I think going forward using std::print will be a wonderful thing, but that does not dismiss the useful news of stream objects! See more: https://en.cppreference.com/w/cpp/io/print
// SimpleOutput_cpp23.cpp
import std;
int main(){
std::print("Hello my programming friends!\n");
return 0;
}
For now, I want to focus on text input and output.
Behind the scenes it's important to understand what is going on when we process some data.
Often times when starting to program, I'll observe students writing little debug messages like std::cout << "I am here" << std::endl;
in thier code. And while that is fine, we really should instead perefer std::cerr
. The reason for this, is that std::cerr
will make sure to write out the entirety of the message if the program crashes, which in some cases will not happen with std::cout
.
Another note, often times you'll see me write
std::endl
at the end of my std::cout statements. The reason is thatstd::endl
will always flush out whatever is in thestd::cout
object. For performance, constantly flushing the buffer can be bad (thus '\n' is preferred to end a line), though for the examples I present, the performance loss for constantly flushing the buffer is negligible.
In C++, one of the mechanisms for handling input and output is a stream object. We have at least two that we want to become familiar with: std::cout
and std::cin
TODO
TODO
TODO
TODO, talk about fstream, ostream, istream, and then std::filesystem (C++17)
TODO
TODO