Input and Output in C++. Streams
After we learned what are variables, we are ready to talk in more details about output in C++. Also we'll discuss how to get user input in console applications.
In C language we used printf and scanf functions for input/output. In C++ we can also use them. But C++ introduces abstraction that's called streams. Stream is just a sequence of bytes. It can move data into our program (from keyboard, file, network, variable) or out of the program (console, file, network)
Streams doesn't depend on device, they are sequential and they work with characters. From keyboard we get characters one by one, in console we print from top to bottom, character by character. As for files, text editors allow to work in any part of file, but internally any file is just a sequence of bytes. We only interested in text files by now, so for us any file is just a sequence of characters. With C++ streams we can write to files and read from files.
Also we can use streams to receive and send data through network or between different programs, but for now we only discuss keyboard, console and files.
There are four standard streams: cout, cerr, clog for output and cin for input. To be able to work with streams in our program we need to include iostream header file. So for any console app we'll have this line of code at the top:
Let's print some lines with different streams:
By default all these streams output theirs content to console. So after execution of these lines you'll see three lines of text. You can use different streams in different parts of your program: output some calculations to cout, handle exceptions and write error messages to cerr, write logs to clog.
For input you need to use cin stream. It works with different data types.
Insertion and extraction operators in C++
Incertion operator << is used to insert data into the stream. And with extraction operator >> we extract data from the stream. To easy remember them imagine that data moves in the direction of arrows and insertion and extraction are related to streams.
Redirecting i/o streams to files
We can redirect input/output streams to files. We can do that in our program with code. But to do this we'll need more knowledge than we have now. There is an easy way. When you run your program you can point to what files you want to redirect standard i/o:
Program a.exe will get input from input_file, b.exe will write to file output_file and program c.exe will get input from in.txt and write to out.txt.
We'll use this feature a lot in later tutorials
In this tutorial we discussed input/output in C++ language and conception of streams. In later tutorials we'll learn how to work with file streams.