The Member Functions get and put

  1. Every input stream, including the standard input stream cin, has a member function called get to read in one character of input and store it in a variable of type char.

  2. The get function is used as follows:

    Input_Stream.get(Char_Variable);

    The member function get will read a single character from the input stream whose name is Input_Stream and assign it to the char variable whose name is the argument of the get function.

  3. Note that get allows you to read any character, including a blank and the new-line character, '\n'.

  4. For example your program contains the code

    char c1, c2 ,c3;
    cin.get(c1);
    cin.get(c2);
    cin.get(c3);

    and if you type in AB followed by return and then CD followed by return. Then c1 is set to 'A', c2 is set to 'B', but c3 is set to '\n'.

  5. The following loop will read any line of input and echo it exactly, including blanks.

    cout << "Enter a line of input and I will echo it:\n";
    char symbol;
    do
    {
        cin.get(symbol);
        cout << symbol;
    } while (symbol != '\n');
    cout << "That's all for this demonstration.\n";

    A sample output is:

    Enter a line of input and I will echo it:
    Do Be Do 1 2    34
    Do Be Do 1 2    34
    That's all for this demonstration.
    

  6. The member function put is analogous to the member function get except that it is used for output rather than input.

  7. The put function is used as follows:

    Output_Stream.put(Char_Variable);

    The member function put will take a single character from the char variable whose name is the argument of the put function and output it to the output stream whose name is Output_Stream.

  8. To use the get and put functions, your program should contain the directive

    #include <fstream>