C++: The Basics - eps1.5_InputOutput
Where do I come from? Where am I going? Does it all make sense? Philosophers and intellectuals have been dealing with these questions since time immemorial. But so far nobody found a final answer to it.
No, I am not in a crisis of meaning, nor do I intend to live ascetically in Tibet for seven years. It seems to me to be such a fundamental question that it fits just as well to our topic in a modified form.
Where does the data come from?
Where does the processed data go?
Does my programming make any sense at all?
System, System in der Hand, sag mir…
Do you remember our first program? That’s when we had the computer display “Hello World!” on the console. The output on the screen is for you to check if the program is working at all. Without this visual feedback you can hardly see the execution.
What is going on in the program now?
#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
return 0;
}
// listing1: HelloWorld.cpp
In this example we already use the first function from the C++ standard library. std::cout
is the standard output, connected to the monitor. This gives you a simple way to output data in an uncomplicated way.
Note, I deliberately used the phrase “connected to”. Output is not limited to the monitor. You can also connect the standard output to other output devices. Therefore, don’t wear blinders and avoid tunnel vision. Usually the standard output device is still the monitor.
The prefix std::
tells you that the function is in the namespace of the standard library. If the meaning just slipped your mind, just look at eps1.2_TheSkeleton.
Everything must flow
cout
stands for standard output stream and forms an instance of the ostream class. You insert the displayed data into this stream using the <<
operator.
For input and output of sequential media, such as the screen, your keyboard, or files in general, C++ uses the quite handy abstraction of streams. Now, how can you best think of a stream? It’s a construct of consecutive characters that you can either pull out or add more to. The important thing to understand is that a stream is both a source and destination for characters, providing or receiving them sequentially.
The STL defines a few stream objects:
Stream | Description |
---|---|
cin | standard input stream |
cout | standard output stream |
cerr | standard error (output) stream |
clog | standard logging (output) stream |
In other blog entries you will come across cout
or cin
from time to time. cerr
and clog
are also output streams and basically work like cout
. The only difference is that they are meant to highlight specific use cases: error or logging messages.
Come in
The logical next step would be to not just display information and be a passive observer, but to actively interact with the system. This would allow us to interactively exchange information via a two-way communication interface. You certainly know the technical term for a human-computer communication interface: User Interface (UI).
To add one or more characters to a stream, you can use the standard input stream cin
.
cin
is an instance of the istream class and lets you read input from a standardized input device. Often your keyboard is this input device. The extraction operator >>
takes elements from the cin
stream that you type on the keys.
For the correct syntax you write cin
together with the extraction operator >>
. This is followed by the variable where you want to store the input stream data (see listing2).
int value;
cin >> value;
// listing2: input of an integer value
First the integer variable value
is declared. Then the values from the input stream cin
are stored in value
. But which values are in this stream? Where does the data come from?
cin
is directly connected to your keyboard and waits for your input. So the stream consists of every key information you press. The sequence ends with the Enter key. But don’t rush. cin
gives you all the time you need for the input. As soon as the Extraction Operator >>
is reached in the source code, the program waits until you finish your input yourself.
The extration operator looks at the datatype of the variables following it and interprets the data in the stream as such. In listing2 it expects integers.
This becomes problematic at the latest when the operator cannot interpret the input as integer. Then the extraction fails and the program continues without assigning data to the variable. value
then remains empty.
Not quite as severe, but still unintentional, is the case where interpretation is possible. For example, if the user in Listing2 enters the floating point number 3.7, the decimal places are deleted and value
has the value 3.
You also have the option of stringing multiple inputs together. When entering the two values, separate them either with a space or with Enter.
cin >> a >> b;
// listing3: chained statements
You can see that input via standard interfaces using cin
is quite simple. But you have to be careful about what the user can and should enter.
Come in and cout
Up to this point we have learned quite a bit again. Now we want to see all the input and output stuff in action.
A small example:
#include <iostream>
int main()
{
char firstLetter;
float floatNumber;
int intNumber;
std::cout << "Hi, what is the first letter of your name?" << std::endl;
std::cin >> firstLetter;
std::cout << "And now, please tell me a number between 2.0 and 3.0" << std::endl;
std::cin >> floatNumber;
intNumber = floatNumber;
std::cout << "Hey " << firstLetter << ", be careful with the data types, otherwise your " << floatNumber << " will quickly turn into a " << intNumber << "!" << std::endl;
return 0;
}
// listing4: input of an integer value
We learned about all the data types and implicit data conversion in Listing4 in the last blog post. So nothing new. First, in the main()
function, three variables are declared with the datatypes char
,float
and int
.
This is followed by the first output on the console, which asks you to type a letter. The input stream waits for your input and stores it in firstLetter
after your confirmation with Enter.
After that you may choose a number between 2 and 3. After you have entered your number into the stream and the stream is closed, this value is in the variable floatNumber
.
This is followed by a rather messy assignment of floatNumber
to intNumber
. In this implicit conversion of a floating point variable into an interger variable, the decimal places of the number are lost.
You often find inputs and outputs in many programs. They help you to better understand how the programs work in detail and how they process data. It also allows you to check your own programs for errors, as this makes it easy to check your code.
endl vs. \n
This difference falls under the category “good to know…”. Sometimes you will find "\n"
instead of std::endl
at the end of an output stream. At first glance, both seem to serve the same function. Of course there is a “but”.
The difference lies in a small detail. std::endl
not only terminates a line, but takes all data from the stream buffer. Every input to a stream is first buffered. All data received until the output of the buffer will be output at once.
If you don’t want to wait until the buffer empties, you can make it do so with the flush
command. std::endl
has the same function as "\n" << std::flush;
std::cout << std::endl // inserts a new line and flushes the stream
std::cout << "\n" // only inserts a new line.
// listing5: endl or \n
Wenn du also nur eine neue Zeile beginnen möchtest, nimmt ruhig "\n"
. Bist du dir unsicher, wann die Daten aus dem Bufer gelesen werden, oder benötigst genau zu einem Zeitpunkt alle Bufferdaten, dann benutze std::endl
.
That sticks
Today we have dealt with input and output streams. You now know how to take input from your keyboard with std::cin >>
and how to output it to the screen with std::cout <<
. In addition, we now know what streams are, how to start a new line (\n
) and how to flush the stream buffer (std::flush
).
I wish you maximum success!
PS: If you are now wondering about the meaning of life, I would like to recommend you this book. In it you will get an answer with a wink ;-)
English: The Hitchhiker’s Guide to the Galaxy - EAN 9781509886517
Deutsch: Per Anhalter durch die Galaxies - ISBN 978-3-0369-5954-2
Sources
- [1] B. Stroustrup, A Tour of C++. Pearson Education, 2. Auflage, 29. Juni 2018.
- [2] B. Stroustrup, Programming: Principles and Practice Using C++. Addison Wesley, 2. Auflage, 15. Mai 2014.
- [3] U. Breymann, Der C++ Programmierer. C++ lernen – professionell anwenden – Lösungen nutzen. Aktuell zu C++17. München: Carl Hanser Verlag GmbH & Co. KG; 5. Auflage, 6. November 2017