Summary
A program transforms inputs into outputs, and this lesson studies the two ends of that transformation and what can go wrong between them. It teaches how to write with std::print and std::println, with placeholders and format specifications that fix the width, the alignment and the decimals; how to read numbers with std::cin; how to foresee what happens when the user types something other than what was asked for, which, with an input system like that of C++, produces not a warning but a stream in an error state and a variable holding a zero; and how to classify the errors of a program into four kinds, according to the moment at which they show up: compile, link, runtime and logic errors. It ends with the methodical reading of compiler messages.
Learning objectives
- Write programs that read data with
std::cinand write results withstd::println, using format specifications for the width and the decimals. - Predict the exact output of a program with several calls to
std::printandstd::println, line breaks included. - Describe what happens when the input does not have the expected form (letters instead of a number) and check the state of the reading.
- Classify an error as a compile, link, runtime or logic error, and locate it from the way it shows up.
The program and its boundary
In the lesson From the problem to the algorithm each problem was specified by what goes in and what comes out. A program carries out that specification: it receives data, transforms them and delivers results. Now, the data are not born inside the program but outside it, at the keyboard of whoever uses it, in a file or in another program; and the results do not stay inside either, but go to a screen, to a file or to another program. Communication with that outside world takes place through two channels that the operating system opens for every program when it starts it: standard input, which in a terminal is what is typed on the keyboard, and standard output, which is what the terminal shows. C++ represents them as streams: sequences of characters that are consumed or produced in order, one after another.
The two ends are not symmetric. The output is decided by the program, and so it can be written exactly: every character that appears on the screen is the one the program ordered to be written. The input, by contrast, is decided by someone else: the program asks for a number, but whoever is at the keyboard may type a word, a number with a decimal comma, a number that is too large, or nothing. If this is so, the input is an untrusted boundary, and every program that reads data must foresee what it will do when what it receives does not have the expected form. This lesson first teaches how to write, then how to read, then what happens when reading fails, and finally how to recognize errors, those of the program and not those of the user, according to the moment at which they show up.
Loading the content…
Completed
Sign in to save your progress