We have discussed token-oriented input, performed when you use the operator >> on streams and file streams. Token-oriented input reads a token, an item (generally) separated from the next token by whitespace characters. We have also discussed line-oriented input, performed by getline(), which reads an entire line of input. C++ has a third kind of I/O, character-oriented I/O, which reads in or prints out one character at a time. Character-oriented I/O is performed by the functions get() and put().

The get() Function

The stream input function specifically designed for input of a single character value is get(). In its most common form, this function reads a single character (including a whitespace character; remember that whitespace characters are spaces, tabs and newline characters) from the keyboard and returns it. Typically, the value returned is assigned to a variable of type char.

The general form of a call to get() to read a character from an input stream infile into a variable ch:

ch = infile.get();

• The stream can be a file stream, like infile, or it can be cin.

• If it attempts to read past the end of input, the stream variable gets a value indicating failure.

Why Do We Need get()?

You might ask why we need the get() function, since the extraction operator >> is capable of reading a character from a stream. The answer is that the extraction operator will not read whitespace characters. Suppose you want to read all the characters in this line and count them:

This is the string.

If you were to read this string character by character with the >> operator and count the characters, you would read in 16 characters. If you were to read it character by character with get(), you would read in 19 characters, counting the spaces. (And if you were to read it with getline(), you'd read the whitespace characters, but you'd read the whole string at once; and you couldn't count the characters as they are being read in.)

Share To:

Next

This is the most recent post.

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..