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
./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'
orendl
character in buffer
getline()
functionread 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()
methodany input stream has this method
ignore characters until the first delimiter
default delimiter is
\n
std::cin.ignore(std::numeric_limits<std::streamsize>::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'
orendl
character will trigger flushsyntax like
cin.flush()
to force flush
formatting
#include <iomanip>
headerfixed
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 filefail()
if the last read fail
Reading errors
check
eof()
if read errors are not expected to happencheck
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
>>
extractiongetline()
constructor to take a string as parameter
.str()
to take a string as the content.clear()
to clear all contentsend 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
<<
insertionall 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 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 preferredfail()
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 neededend of file check
.eof()
orfail()
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.