Lecture Notes for Introduction to Computer Science II

26 July 2001 - Advanced Formatted I-O


  1. string input

    1. white-space delimiters can be a pain when reading strings - end up with words.

    2. the getline() string member function reads strings

      1. includes white space in the string

      2. reads up to a delimiter character - usually a newline

      3. does not include the delimiter character in the string

  2. stream manipulators

    1. control how formatted i-o behaves on input and output

    2. defined in <iomanip>

    3. set the number base - hex, dec, oct

      1. int i = 135 ; cout << i << " in hex is " << hex << i << "\n"

      2. cout << "Input a hex number: " ; cin >> hex >> i

      3. base manipulators are sticky - the conversion remains once set

        1. this is a pain - some manipulators are not sticky

        2. this is also compiler dependent

      4. also the setbase(i) manipulator where i = 8, 10, or 16

    4. set the field width - setw(i)

      1. on output, use at least i characters to format

        1. cout << setw(5) << 3 produces " 3"

        2. extra characters are blanks, inserted to the left

        3. the full value is always output - no truncation, larger field

        4. cout << setw(1) << 123 produces "123"

      2. can also be used for input, but to what effect

      3. setw() is not sticky

        1. cout << setw(4) << "a" << "b" produces " ab"

        2. cout << setw(4) << "a" << setw(4) << "b" produces " a b"

    5. the setfill(c) manipulator - use character c as the pad

      1. cout << setw(5) << setfill('*') << 1 produces "****1"

      2. setfill() is sticky

    6. the setiosflags() manipulator - modify control bits

      1. ios::left - left justify output; "1 "

      2. ios::right - right justify output; " 1"

      3. ios::showpoint - output floating point with a dot and zeros

      4. ios::skipws - skip whitespace on input; also the ws manipulator; this usually doesn't do what you want

      5. ios::scientific - output floating point in scientific notation; also(ios::fixed

      6. ios::uppercase - output uppercase hex digits; also ios::lowercase

      7. these are sticky - undone by the resetiosflags() manipulator

    7. most manipulators are available as member functions too

      1. the setw() manipulator and the width() stream member function

      2. the setfill() manipulator and the fill() stream member function

      3. the setiosflags() manipulator and the setf() stream member function - also unsetf()

    8. other manipulators

      1. endl - output a newline

      2. flush - force output


This page last modified on 27 July 2001.