# C++ Notes: Reading Characters

These notes are written using `cin` as an example, but they apply to all input streams.

## What about whitespace?

The standard input stream (`cin`) does just what you want when reading integers, floating point etc. It ignores all whitespace (blanks, tabs, etc) that appears in front of a number. But when you're reading characters, you will often want to read whitespace too. For example, here's a little loop to count the number of characters in the input stream.

    char c;
    int  count = 0;
    while (cin >> c) {  // DOESN'T READ WHITESPACE!!!!!
        count++;
    }

The fails to give an accurate count of characters because it ignores all the whitespace characters. There are two solutions.

- Use the `noskipws` I/O manipulator to cause a further `cin` reads to not ignore whitespace (or until the `skipws` manipulator is used). Here's that same loop rewritten.

      char c;
      cin >> noskipws;    // Stops all further whitespace skipping
      while (cin >> c) {  // Reads whitespace chars now.
          count++;
      }

  This isn't a bad solution, but choose the next alternative to always read whitespace with no need to switch the mode of the `cin` stream.
- Use the `cin.get()` function.

      char c;
      while (cin.get(c)) {  // Always reads whitespace chars.
          count++;
      }

## Skipping input

When an error is encountered, it is often useful to skip all remaining characters on the line. You can do that with:

    cin.ignore(n, c);

where n is the number of characters to skip, and c is the character to skip up to, whichever comes first. For example, to skip to the end of the line,

    cin.ignore(1000, '\n');