Streams
Streams
A
stream is an object that transports and formats characters of fixed width.
Stream Libraries
istream - input stream
ostream - output stream
iostream - both input and output stream. Has the following children libararies: ifstream, ofstream, fstream, istringstream, ostringstream, stringstream
Stream Operators
- Inserter Operator
<<
- Extractor Operator
>>
- Parse information expected by destination object according to its type
Console I/O
-
Output with
cout: outputs text to stdout. Used with inserter operator <<. Allows for chaining of strings/variables by adding inserters and the additional strings/variables to the right side. endl represents a newline character.
-
Input with
cin - reads stdin and stores input value into specified variable. Used wth extractor operator >>. Only reads up to a whitespace character (space, tab, newline)
-
Output with
cerr - sends its output to stderr. Allows a way to distinguish normal output and error messages. Works in the same way as cout.
Formatting Output
The output format can also be formatted. For example, if we wanted all floats to be represented with 2 decimals places, we add the following statements:
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
Any following
cout statements that follow will output floats rounded to 2 decimal places.
File I/O
Similar to console I/O, programs can do file I/O to perform reading and writing to files.
Opening a text file
#include <fstream>
using namespace std;
ifstream inputStream;
inputStream.open("player.txt");
assure(inputStream, "player.txt"); // ensures that file is successfully opened
inputStream >> score >> firstName >> lastName;
Another way to open a file is by
ifstream in ('player.txt');
Input Operations
Stream Error State Flags
Error state flags are used to keep track of the stream's state.
eofbit - end-of-file is reached
failbit - last input operation failed due to internal logic
badbit - error due to failure of an I/O operation on the stream buffer
goodbit - no error / absence of above error state flags
String <=> Integer
stringstream can be used to convert strings to and from integers.
String to Integer
#include <sstream>
#include <string>
using namespace std;
string s = "42 30";
istringstream iss (s);
int x, y;
iss >> x >> y;
Integer to String
ostringstream oss;
oss << 23 << "+" << 124;
string s = oss.str();