.. highlight:: c++ :linenothreshold: 5 ****************** Input/Output (I/O) ****************** General Info ============ Input/output related logics are essential components in many computational tasks including interaction with users, file read/write, string parsing/generation .. note:: It is always a good practice to group I/O related logics in a minimal number of classes/functions because they are not testable with automatic testing. Stream Based I/O ================ All I/O covered in this section is about stream based I/O which handles data as sequential structures. There are many other I/O patterns. For instance, with block I/O the program read/write data as blocks. Standard I/O ============ + Input/output in the command-line context * keyboard input as standard input * terminal character print/display as standard output + iostream - the input/output stream library header + Standard input * std::cin * a global variable that you can use anywhere in your program * an instance/object of the istream class + Standard output * std::cout * a global variable that you can use anywhere in your program * an instance/object of the ostream class + Standard Error * std::cerr * a global variable that you can use anywhere in your program * an instance/object of the ostream class * used to display error messages + Redirection In UNIX shells, you can redirect standard I/O using operators like ``<``, ``>``, ``|``. * ``<`` to redirect standard input from a file * ``>`` to redirect standard output to a file * ``|`` to pipeline the standard output of the last command as the standard input of the next program .. code-block:: bash ./main < input.txt ./main > output.txt ./main < input.txt > output.txt ./cat input.txt | ./main Input/Output Operations ======================= + Input operations * Extraction operator ``>>`` - work with any input stream including cin - can be chained - can be used as a boolean value (true if the operation succeed, false otherwise) - read and convert to desired type - will leave ``'\n'`` or ``endl`` character in buffer * ``getline()`` function - read in a line as string: ``getline(cin, inputString);`` - work with any input stream including cin - read in string only - may read in empty string - **special handling when used after extraction** - may use other delimiter i.e. ``getline(cin, inputString, ',');`` .. warning:: differentiate it from the ``cin.getline()`` function! * ``ignore()`` method - any input stream has this method - ignore characters until the first delimiter - default delimiter is ``\n`` - ``std::cin.ignore(std::numeric_limits::max(), '\n');`` to be used after ``>>`` to remove the rest of the line + Output operations * Insertion operator ``<<`` - work with any output stream including cout - can be chained - buffered, display upon flushing + inserting ``'\n'`` or ``endl`` character will trigger flush + syntax like ``cin.flush()`` to force flush - formatting + ``#include `` header + ``fixed`` + ``showpoint`` + ``scientific`` + ``setprecision()`` + ``setw()`` + ``setfill()`` + ``left`` + ``right`` .. note:: All above manipulators are sticky except ``setw``. Sticky means that once it is set, it will be affective until it is set again later. However, the effect of setw will only affect the next insertion operation. + Error handling Stream operations are likely to fail. Error handling is essential. * Methods - ``eof()`` if the last successful read hit the end of the file - ``fail()`` if the last read fail * Reading errors - check ``eof()`` if read errors are not expected to happen - check ``fail()`` if read errors are likely to happen * Writing errors String I/O ========== Used for text parsing or formatted string generation * sstream header * istringstream class - an input stream based on the content of a string - ``>>`` extraction - ``getline()`` - constructor to take a string as parameter - ``.str()`` to take a string as the content - ``.clear()`` to clear all contents - end of file check + ``.eof()`` call after every read (extraction, getline) + Extraction operation as bool value ``while (inSS >> value) ...`` * ostringstream class - an output stream accept formatted output and generate a string - ``<<`` insertion - all formatting tools from iomanip will work - ``.str()`` method to generate a string containing the content in the stream .. note:: You can also manipulate strings using string methods. Check the :ref:`string document ` for more information. File I/O ======== + fstream header + ifstream class * read from a file + ofstream class * write to a file + bind to a file * pass the path string to the constructor * call ``.open()`` method with the path string + ``open()`` * methods to check open status - ``is_open()`` is preferred - ``fail()`` * very likely to fail so must check status after opening - read a non-existing file - write a existing file - other file system problems + ``close()`` should be called when the file stream is no longer needed + end of file check * ``.eof()`` or ``fail()`` function call after read operations (extraction, getline) * simplified syntax to check the status of reading (same as check fail()) - ``while (inFS >> value) { ... }`` - ``while (getline(inFS, line)) { ... }`` .. warning:: ``while (inFS >> value)`` will work but ``while (inFS >> value == true)`` will fail! The expression must be directly used in the parenthesis. Same rule applies to ``getline(inFS, line)`` call.