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.
Read one line with cin.get(...) or cin.getline(...)
char ca[100];
. . .
while (cin.get(ca)) {
// ca has one input line without crlf and with terminating 0
. . .
}
Ignoring 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');