- Forward


Input/Output in C++
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • C and C++ handle I/O in very different ways
  • It is useful to know both, especially since you may wind up working with people that use both
Getting Started
Back SMYC Forward
  • Streams:
    • A stream can be thought of as a flow (or sequence) of objects (e.g., characters, bytes)
    • Input involves taking objects from the stream
    • Output involves adding objects to the stream
  • A Portion of the Class Hierarchy:
    • cpp_io
  • Common Practice:
    • One generally includes either <iostream> or <fstream>, rather than one of their parents
Stream Objects
Back SMYC Forward
  • Declaration:
    • Exactly the same as with other objects
  • Example:
    • ifstream input_file; ofstream output_file;
Using the Console
Back SMYC Forward
  • Standard In and Out:
    • If you only need to use "console I/O" or "standard in" and "standard out" (which java calls System.in and System.out) you can use the streams cin and cout
  • Other Standard Output Files in <iostream>:
    • cerr
    • clog
  • Something to Remember:
    • These streams need to be fully-qualified (using std::) or you need to include the statement using namespace std;
Using the Console (cont.)
Back SMYC Forward
  • An Example:
    • std::cout << "Hi Mom! \n";
  • Some Details:
    • << and >> are operators (more on them shortly)
    • cin is actually an object of type istream_withassign (which is a class that inherits from istream)
    • cout, cerr, clog are actually objects of type ostream_withassign (which is a class that inherits from ostream)
Opening and Closing Streams
Back SMYC Forward
  • The Issue:
    • Streams need to be opened before they can be used and closed when you are through with them
    • The standard streams are opened and closed for you
  • The Methods:
    • void open(const char *name, int mode)
    • void close(void)
  • The Parameters:
    • name is the name of the stream/file
    • mode is the I/O mode
I/O Modes
Back SMYC Forward
  • Approach:
    • Each bit represents a different property
  • Flags (defined in the ios class):
    • ios::app Open for append
      ios::ate Go to the end
      ios::in Open for input (required for ifstream)
      ios::out Open for output (required for ofstream)
      ios::binary Binary file
      ios::trunc Discard existing contents
I/O Modes (cont.)
Back SMYC Forward
  • Using Flags:
    • To set more than one bit, simply OR the appropriate flags together
  • An Example:
    • ofstream output_file; output_file.open("sales.dat", (ios::out | ios::app | ios::nocreate) );
Testing the State of a Stream
Back SMYC Forward

int bad() Returns non-zero if the previous I/O operation failed and data were lost
int good() Returns non-zero if the previous I/O operation succeeded
int eof() Returns non-zero if previous read succeeded and the stream is empty
int fail() Returns non-zero if previous I/O operation failed

Writing ASCII Streams
Back SMYC Forward
  • The Insertion Operator (<<):
    • Inserts an ASCII string into a stream (i.e., the left-hand-side operand)
    • If the right-hand operand is not an ASCII string, the insertion operator will attempt to convert it into one
  • An Example:
    • std::cout << "Go Dukes!";
  • Another Example:
    • int earnings; earnings = 10000; std::cout << "I earned " << earnings << " dollars this month";
Reading ASCII Streams
Back SMYC Forward
  • The Extraction Operator (>>):
    • Extracts a sequence of ASCII characters from a stream (i.e., the left-hand-side operand) and converts these characters into one of the built-in data types
  • An Example:
    • int orderNumber; cin >> orderNumber;
  • Some Details:
    • Consumes and discards any leading whitespace
    • For numeric data, the extraction stops at the first inappropriate character (for the data type)
Some Other Useful Methods
Back SMYC Forward

get Extract a single character or a string (including whitespace)
getline Extract a full "line" of characters
ignore Discards a given number of characters
putback Inserts a character back into the input stream after it has been read

An Example
Back SMYC Forward

A File Splitter

cppexamples/io/FileSplitter.cpp
 
Formatted ASCII I/O
Back SMYC Forward
  • Formats:
    • Many applications have to generate output in a particular format and/or read input files that are formatted in a particular way
  • Approaches in C++:
    • This can be accomplished by setting format bits or using manipulators
Using Format Bits
Back SMYC Forward
  • Methods:
    • setf(int flags)
    • unsetf(int flags)
  • Flags (in the ios class):
    • ios::skipws Skip leading whitespace on input
      ios::left Left-justify output
      ios::right Right-justify
      ios::internal Pad between sign and number on output
      ios::dec Output in base 10
      ios::oct Output in base 8
      ios::hex Output in base 16
      ios::showbase Include a base indicator on output
      ios::showpoint Always include a decimal point n output
      ios::uppercase For hexadecimal digits on output
      ios::showpos Always include a + or -
      ios::scientific Output in scientific notation
      ios::fixed Output as fixed-point numbers
Using Format Bits (cont.)
Back SMYC Forward
An Example

using namespace std; cout.setf(ios::hex | ios::showbase | ios::uppercase ); cout << 1023;

The Result

    0x3FF
    

Using Manipulators
Back SMYC Forward
  • The Idea:
    • Manipulators are inserted into the stream itself to change the format
  • Some Manipulators (in <iomanip>)
    • setiosflags(long flags) Set the format bits
      resetiosflags(long flags) Reset the format bits
      ws Skip whitespace on input
      dec Output in base 10
      oct Output in base 8
      hex Output in base 16
      setw(int width Set the width of the output
      setprecision(int precision) Set the precision of floating point output
      setfill(char c) Set the fill character
      endl End of line (i.e., '\n')
      ends End of string (i.e., '\0')
Using Manipulators (cont.)
Back SMYC Forward
An Example

#include <iostream> #include <iomanip> using namespace std; int n; n = 12; cout << setw(5) << n << "\n";

The Result

Three spaces and then the two-digit number 12

Reading and Writing Binary Streams
Back SMYC Forward
  • The read and write methods:
    • Have two parameters, a pointer to a variable and the size of the item being read (in bytes)
  • An Example:
    • inputFile.read(&n, sizeof(n));
    • The sizeof function returns the size (in bytes) of its argument
    • The & operator provides the address of the variable n (more on this later)
Portability of Binary Files
Back SMYC Forward
  • Unix uses one character at the end of lines (i.e., '\n') whereas MS-DOS uses two (i.e., '\r' and '\n')
  • Different machines order bytes differently. For example, the short int 0x1234 consists of of two bytes (i.e., 0x12 and 0x34). Some systems write the low-order byte first (e.g., systems with Intel processors) and others write the high-order byte first (e.g., systems with Motorola 68000 processors).
  • Some machines limit the addresses that can be used for different data types
Random/Direct Access
Back SMYC Forward
  • The Concept:
    • It is sometimes convenient to be able to move around in a file without reading from it or writing to it
  • Positioning the Read Head ("get pointer"):
    • seekg
  • Positioning the Write Head ("put pointer"):
    • seekp
Random/Direct Access (cont.)
Back SMYC Forward
An Example

inputFile.seekg(300);

Explained

Moves the read head to byte number 300

Random/Direct Access (cont.)
Back SMYC Forward
Another Example

inputFile.seekg(-100, ios::end); inputFile.seekg(10, ios::cur);

Explained

First moves the read head to the position 100 bytes prior to the end of the file and then moves it 10 bytes forward from that position

Random/Direct Access (cont.)
Back SMYC Forward
  • Determining the Current Position:
    • The tellg() and tellp() methods will return the current position of the read and write heads, respectively
  • Limitations:
    • Some devices, like the keyboard, are inherently sequential. Hence, they will not support random access
There's Always More to Learn
Back -