Cstring I/O

  1. Cstrings can be output using the insertion operator <<.

  2. A cstring variable can be filled using the input operator >>. However you have to remember that
    • all leading whitespaces (blanks, tabs and line breaks) in the input stream are skipped,
    • and each reading of input stops at the next whitespace character (a blank, a tab or a line-break character).

  3. For example, the following code:

    char a[80], b[80];
    cout << "Enter some input:\n";
    cin >> a >> b;
    cout << a << b << "END OF OUTPUT\n";

    produces the output:

    Enter some input:
    Do be do to you!
    DobeEND OF OUTPUT

    The cstring a receives the value "Do" and b receives "be".

  4. Thus cin >> actually reads one word at a time.

  5. To read an entire line of input, the predefined member function getline can be used.

  6. The function getline is a member function of every input stream such as cin or a file input stream.

  7. The syntax of the getline function:

    Input_Stream.getline(Cstring_Var, Max_Size);

    One line of input is read from the stream Input_Stream and the resulting cstring is placed in Cstring_Var. Only the first (Max_Size - 1) characters are read even if the line has more characters. The last character in Cstring_Var is always the null character.

  8. For example, the following code:

    char a[80];
    cout << "Enter some input:\n";
    cin.getline(a, 80);
    cout << a << "END OF OUTPUT\n";

    may produce a dialogue like:

    Enter some input:
    How is George Bush doing?
    How is George Bush doing?END OF INPUT

    Note that input ends with the newline character, even though the second argument of the getline function allows up to 80 characters to be read.

  9. Reading stops after the number of character specified by the second argument of the getline function have been filled, even if the end of the line has not been reached.

    For example, the following code:

    char a[8];
    cout << "Enter some input:\n";
    cin.getline(a, 8);
    cout << a << "END OF OUTPUT\n";

    may produce a dialogue like:

    Enter some input:
    Happy Easter!
    Happy EEND OF INPUT

    Note that only 7 not 8 characters are read into the cstring variable a because the last element of a is filled by the null character.

  10. The above cstring I/O techniques work exactly the same if cout and cin are replaced by an output file stream and an input file stream that has been connected to an appropriate external file using the member function open.