C++ Programming/Code/IO

I/O
Also commonly referenced as the C++ I/O of the C++ Standard Library, since the library also includes the C Standard library and its I/O implementation, as seen before in the Standard C I/O Section.

Input and output are essential for any computer software, as these are the only means by which the program can communicate with the user. The simplest form of input/output is pure textual, i.e. the application displays in console form, using simple ASCII characters to prompt the user for inputs, which are supplied using the keyboard.

There are many ways for a program to gain input and output, including
 * File i/o, that is, reading and writing to files
 * Console i/o, reading and writing to a console window, such as a terminal in UNIX-based operating systems or a DOS prompt in Windows.
 * Network i/o, reading and writing from a network device
 * String i/o, reading and writing treating a string as if it were the input or output device

While these may seem unrelated, they work very similarly. In fact, operating systems that follow the POSIX specification deal with files, devices, network sockets, consoles, and many other things all with one type of handle, a file descriptor. However, low-level interfaces provided by the operating system tend to be difficult to use, so C++, like other languages, provide an abstraction to make programming easier. This abstraction is the stream.

Streams
A stream is a type of object from which we can take values, or to which we can pass values. This is done transparently in terms of the underlying code that demonstrates the use of the std::cout stream, known as the standard output stream.

Almost all input and output one ever does can be modeled very effectively as a stream. Having one common model means that one only has to learn it once. If you understand streams, you know the basics of how to output to files, the screen, sockets, pipes, and anything else that may come up.

A stream is an object that allows one to push data in or out of a medium, in order. Usually a stream can only output or can only input. It is possible to have a stream that does both, but this is rare. One can think of a stream as a car driving along a one-way street of information. An output stream can insert data and move on. It (usually) cannot go back and adjust something it has already written. Similarly, an input stream can read the next bit of data and then wait for the one that comes after it. It does not skip data or rewind and see what it had read five minutes ago.

The semantics of what a stream's read and write operations do depend on the type of stream. In the case of a file, an input file stream reads the file's contents in order without rewinding, and an output file stream writes to the file in order. For a console stream, output means displaying text, and input means getting input from the user via the console. If the user has not inputted anything, then the program blocks, or waits, for the user to enter in something.

iostream
  is a header file used for input/output. It is part of the C++ standard library. The name stands for Input/Output Stream. In C++ there is no special syntax for streaming data input or output. Instead, these are combined as a library of functions. Like we have seen with the C Standard Library use of  header,   provides basic OOP services for I/O.

The  automatically defines and uses a few standard objects: for sending data to and from the standard streams input, output, error (unbuffered), and error (buffered) respectively. As part of the C++ standard library, these objects are a part of the std namespace.
 *  , an object of the istream class that reads data from the standard input device.
 *  , an object of the ostream class, which displays data to the standard output device.
 *  , another object of the ostream class that writes unbuffered output to the standard error device.
 *  , like cerr, but uses buffered output.

The most common streams one uses are cout, cin, and cerr (pronounced "c out", "c in", and "c err(or)", respectively). They are defined in the header  . Usually, these streams read and write from a console or terminal. In UNIX-based operating systems, such as Linux and Mac OS X, the user can redirect them to other files, or even other programs, for logging or other purposes. They are analogous to stdout, stdin, and stderr found in C. <tt>cout</tt> is used for generic output, <tt>cin</tt> is used for input, and <tt>cerr</tt> is used for printing errors. (<tt>cerr</tt> typically goes to the same place as <tt>cout</tt>, unless one or both is redirected, but it is not buffered and allows the user to fine-tune which parts of the program's output is redirected where.)
 * Standard input, output, and error

Output
The standard syntax for outputting to a stream, in this case, <tt>cout</tt>, is

Example

Result of Execution Hello, World! 1

To add a line break, send a newline character, <tt>\n</tt>. Using  also outputs a newline character, but it also calls os.flush.

Example

Execution Hello, World! 1

It is always a good idea to end your output with a blank line, so as to not mess up with user's terminals.

As seen in the "Hello, World!" program, we direct the output to. This means that it is a member of the standard library. For now, don't worry about what this means; we will cover the library and namespaces in later chapters.

What you do need to remember is that, in order to use the output stream, you must include a reference to the standard IO library, as shown here:

This opens up a number of streams, functions and other programming devices that we can now use. For this section, we are interested in two of these;  and.

Once we have referenced the standard IO library, we can use the output stream very simply. To use a stream, give its name, then pipe something in or out of it, as shown:

The <tt> << </tt> operator feeds everything to the right of it into the stream. We have essentially fed a text object into the stream. That's as far as our work goes; the stream now decides what to do with that object. In the case of the output stream, it's printed on-screen.

We're not limited to only sending a single object type to the stream, nor indeed are we limited to one object a time. Consider the examples below:

As can be seen, we feed in various values, separated by a pipe character. The result comes out something like:

Hello, Joe The answer to life, the universe and everything is 42

You will have noticed the use of <tt>std::endl</tt> throughout some of the examples so far. This is a special manipulator, which not only outputs a newline character but also calls os.flush.

Input
What would be the use of an application that only ever outputted information, but didn't care about what its users wanted? Minimal to none. Fortunately, inputting is as easy as outputting when you're using the stream.

The standard input stream is called <tt>std::cin</tt> and is used very similarly to the output stream. Once again, we instantiate the standard IO library:

This gives us access to <tt>std::cin</tt> (and the rest of that class). Now, we give the name of the stream as usual, and pipe output from it into a variable. A number of things have to happen here, demonstrated in the example below:

We instantiate the standard IO library as usual, and call our main function in the normal way. Now we need to consider where the user's input goes. This calls for a variable (discussed in a later chapter) that we declare as being called <tt>a</tt>.

Next, we send some output, asking the user for their age. The real input happens now; everything the user types until they hit Enter is going to be stored in the input stream. We pull this out of the input stream and save it in our variable.

Finally, we output the user's age, piping the contents of our variable into the output stream.

Note: You will notice that, if anything other than a whole number is entered, the program will crash. This is due to the way in which we set up our variable. Don't worry about this for now; we will cover variables later on.

A Program Using User Input
The following program inputs two numbers from the user and prints their sum:

Just like <tt>std::cout</tt> that represents the standard output stream, the C++ library provides (and the <tt>iostream</tt> header declares) the object <tt>std::cin</tt> representing standard input, which usually gets input from the keyboard. The statement:

uses the extraction operator (<tt>>></tt>) to get an integer input from the user. When used to input integers, any leading whitespace is skipped, a sequence of valid digits optionally preceded by a <tt>+</tt> or <tt>-</tt> sign is read and the value stored in the variable. Any remaining characters in the user input are not consumed. These would be considered next time some input operation is performed.

If you want the program to use a function from a specific namespace, normally you must specify which namespace the function is in. The above example calls to <tt>cout</tt>, which is a member of the <tt>std</tt> namespace (hence <tt>std::cout</tt>). If you want a program to specifically use the std namespace for an identifier, which essentially removes the need for all future scope resolution (e.g. <tt>std::</tt>), you could write the above program like this:

Please note that 'std' namespace is the namespace defined by standard C++ library.

Manipulators
A manipulator is a function that can be passed as an argument to a stream in different circumstances. For example, the manipulator 'hex' will cause the stream object to format subsequent integer input to the stream in hexadecimal instead of decimal. Likewise, 'oct' results in integers displaying in octal, and 'dec' reverts back to decimal.

Example

Execution 16 10 20 12 10 a

There are many manipulators that can be used in conjunction with streams to simplify the formatting of input. For example, 'setw' sets the field width of the data item next displayed. Used in conjunction with 'left' and 'right'(that set the justification of the data), 'setw' can easily be used to create columns of data.

Example

Execution 90  Help! 45       Hi!

The data in the top row display at the right of the columns created by 'setw', while in the next row, the data is left justified in the column. Please note the inclusion of a new library 'iomanip'. Most formatting manipulators require this library.

Here are some other manipulators and their uses:

Buffers
Most stream objects, including 'cout' and 'cin', have an area in memory where the information they are transferring sits until it is asked for. This is called a 'buffer'. Understanding the function of buffers is essential to mastering streams and their use.

 Example 

 Execution 1  >74 >27 Number1: 74 Number2: 27

The inputs are given separately, with a hard return between them. '>' denotes user input.

 Execution 2  >74 27 Number1: 74 Number2: 27

The inputs are entered on the same line. They both go into the 'cin' stream buffer, where they are stored until needed. As 'cin' statements are executed, the contents of the buffer are read into the appropriate variables.

 Execution 3  >74 27 56 Number1: 74 Number2: 27

In this example, 'cin' received more input than it asked for. The third number it read in, 56, was never inserted into a variable. It would have stayed in the buffer until 'cin' was called again. The use of buffers can explain many strange behaviors that streams can exhibit.

 Example 

 Execution  >45 89 37 Number1: 45 Number2: 89 Number3: 37

Notice how all three numbers were entered at the same time in one line, but the stream only pulled them out of the buffer when they were asked for. This can cause unexpected output, since the user might accidentally put an extra space into his input. A well written program will test for this type of unexpected input and handle it gracefully.

ios
ios is a header file in the C++ standard library that defines several types and functions basic to the operation of iostreams. This header is typically included automatically by other iostream headers. Programmers rarely include it directly.

fstream
With <tt>cout</tt> and <tt>cin</tt>, we can do basic communication with the user. For more complex io, we would like to read from and write to files. This is done with file stream classes, defined in the header <tt> </tt>. <tt>ofstream</tt> is an output file stream, and <tt>ifstream</tt> is an input file stream.

To open a file, one can either call <tt>open</tt> on the file stream or, more commonly, use the constructor. One can also supply an open mode to further control the file stream. Open modes include
 * Files
 * ios::app Leaves the file's original contents and appends new data to the end.
 * ios::out Outputs new data in the file, removing the old contents. (default for ofstream)
 * ios::in Reads data from the file. (default for ifstream)

Example

The call to  can be omitted, if you do not care about the return value (whether it succeeded); the destructors will call close when the object goes out of scope.

If an operation (e.g. opening a file) was unsuccessful, a flag is set in the stream object. You can check the flags' status using the  or   member functions, which return a boolean value. The stream object doesn't throw any exceptions in such a situation; hence manual status check is required. See reference for details on  and.

Text input until EOF/error/invalid input
Input from the stream <tt>infile</tt> to a variable <tt>data</tt> until one of the following:
 * EOF reached on <tt>infile</tt>.
 * An error occurs while reading from <tt>infile</tt> (e.g., connection closed while reading from a remote file).
 * The input item is invalid, e.g. non-numeric characters, when <tt>data</tt> is of type <tt>int</tt>.

Note that the following is not correct:

This will cause the last item in the input file to be processed twice, because <tt>eof</tt> does not return true until input fails due to EOF.

ostream
It is often useful to have your own classes' instances compatible with the stream framework. For instance, if you defined the class Foo like this:
 * Classes and output streams

You will not be able to pass its instance to cout directly using the '<<' operator, because it is not defined for these two objects (Foo and ostream). What needs to be done is to define this operator and thus bind the user-defined class with the stream class.

Now this is possible:

The operator function needs to have 'ostream&' as its return type, so chaining output works as usual between the stream and objects of type Foo:

This is because (cout << my1) is of type ostream&, so the next argument (my2) can be appended to it in the same expression, which again gives an ostream& so my3 can be appended and so on.

If you decided to restrict access to the member variables  and   (that is probably a good idea) within the class Foo, i.e.:

you will have trouble, because << function doesn't have access to the private variables of its second argument. There are two possible solutions to this problem:

1. Within the class Foo, declare the << function as the classes' friend that grants it access to private members, i.e. add the following line to the class declaration:

Then define the operator<< function as you normally would (note that the declared function is not a member of Foo, just its friend, so don't try defining it as Foo::operator<<).

2. Add public-available functions for accessing the member variables and make the << function use these instead:

‎Rounding number example
This is a small example that rounds a number to a string, a function called. Figures may have trailing zeros, those that would be expected to disappear using a number format.

The constant class contains repeating constants that should exist only once in the code so that to avoid inadvertent changes. (If the one constant is changed inadvertently, it is most likely to be seen, as it is used at several locations.)

The code was first cross-compiled by the JAVA TO C++ CONVERTER of Tangible Software Solutions. Parts may have a copyright notice requirement that prevents inclusion in this work you can get yourself the code for the  at that location.

Here is the relevant code and its call. You are invited to write a shorter version that gives the same result.





The  class is an enhancement to the   library and contains the rounding calculations.





Using precompiled headers requires the StdAfx files:





The  class was added by the JAVA TO C++ CONVERTER during the crosscompilation:





Extensive testing of a software is crucial for qualitative code. To say that the code is tested does not give much information. The question is what is tested. Not in this case, but often it is also important to know where (in which environment) it was tested, and how - i.e. the test succession. Here is the code used to test the  class.





The results of your better code should comply with the result I got:

Maths::RoundToString(5, '.', 0.00000000000000000) = 0.00000 Maths::RoundToString(5, '.', -1.40129846432482020e-045) = -1.4012e-45 Maths::RoundToString(5, '.', 1.40129846432482020e-045) = 1.4013e-45 Maths::RoundToString(5, '.', -1.99999975700000000e-005) = -1.9998e-5 Maths::RoundToString(5, '.', 1.99999975700000000e-005) = 2.0000e-5 Maths::RoundToString(5, '.', -0.00019999997570000) = -0.00019999 Maths::RoundToString(5, '.', 0.00019999997570000) = 0.00020000 Maths::RoundToString(5, '.', -0.00064058900000000) = -0.00064058 Maths::RoundToString(5, '.', 0.00064058900000000) = 0.00064059 Maths::RoundToString(5, '.', -0.00199999975700000) = -0.0019999 Maths::RoundToString(5, '.', 0.00199999975700000) = 0.0020000 Maths::RoundToString(5, '.', -0.33968999981880188) = -0.33967 Maths::RoundToString(5, '.', 0.33968999981880188) = 0.33968 Maths::RoundToString(5, '.', -0.34000000000000002) = -0.33999 Maths::RoundToString(5, '.', 0.34000000000000002) = 0.34000 Maths::RoundToString(5, '.', -7.07000000000000030) = -7.0699 Maths::RoundToString(5, '.', 7.07000000000000030) = 7.0700 Maths::RoundToString(5, '.', -118.18800000000000000) = -118.18 Maths::RoundToString(5, '.', 118.18800000000000000) = 118.19 Maths::RoundToString(5, '.', -118.20000000000000000) = -118.19 Maths::RoundToString(5, '.', 118.20000000000000000) = 118.20 Maths::RoundToString(5, '.', -123.40500900000001000) = -123.40 Maths::RoundToString(5, '.', 123.40500900000001000) = 123.41 Maths::RoundToString(5, '.', -30.76994323730469100) = -30.768 Maths::RoundToString(5, '.', 30.76994323730469100) = 30.770 Maths::RoundToString(5, '.', -130.76994323730469000) = -130.75 Maths::RoundToString(5, '.', 130.76994323730469000) = 130.77 Maths::RoundToString(5, '.', -540.00000000000000000) = -539.99 Maths::RoundToString(5, '.', 540.00000000000000000) = 540.00 Maths::RoundToString(5, '.', -12345.00000000000000000) = -12344 Maths::RoundToString(5, '.', 12345.00000000000000000) = 12345 Maths::RoundToString(5, '.', -123456.00000000000000000) = -123450 Maths::RoundToString(5, '.', 123456.00000000000000000) = 123460 Maths::RoundToString(5, '.', -540911.00000000000000000) = -540900 Maths::RoundToString(5, '.', 540911.00000000000000000) = 540910 Maths::RoundToString(5, '.', -9.22337203685477560e+056) = -9.2232e56 Maths::RoundToString(5, '.', 9.22337203685477560e+056) = 9.2234e56

If you are interested in a comparison of C++ with C#, take a look at C# programming rounding number example. If you want to compare C++ with Java, compare it to the rounding code at Java Programming rounding number example.

|I