ignore.cpp

What really happens when a user enters data into a C++ program? Suppose that the program is reading an int:

int counter;
cin >> counter;

Consider the steps that take place when the above code fragment runs: a user types in an appropriate value and then press the Enter key to signal that the computer should read and process the data. But pressing the enter key does more than just signal the computer to read the input: it also enters a new line character into the input stream. The input may look something like this: 123\n where the "\n" is the escape sequence for the newline character. The new line character is automatically discarded when reading integers or a floating point values. But the new line character is left in the input stream when a character is read.

while (true)
{
	cout << "A\tAdd\n";
	cout << "S\tSub\n";
	cout << "M\tMult\n";
	cout << "D\tDiv\n";
	cout << "E\tExit\n";

	cout << Operation: ";
	char operation;
	cin >> operation;

	switch (operation)
	{
		.
		.
		.
	}
}
(a)
The input stream depicted as two adjacent boxes. The first box contains
the character A and the second contains a new line character.
(b)
The input stream now depicted as a single box containing a new line.
(c)
The input stream depicted as three boxes: new line, S, new line. The
three boxes represent the situation after reading and removing the A from the input stream and then entering
a S followed by a new line.
(d)
Reading a single character leaves a new line character in the input stream.
  1. A code fragment that iteratively prints a simple menu, prompts the user to select an operation by choosing one of the menu options, and reads the option.
  2. The state of the input stream after the user types "A" and presses the Enter key but before the computer reads a character.
  3. The state of the input stream ofter the "A" is read during the first loop iteration.
  4. The state of the input stream during the second iteration of the loop: the user types "S" followed by pressing the Enter key. The next read operation will attempt to read the new line character rather than the "S".

The ignore function solves this problem that is unique to reading or extracting characters from the console input stream. Adding a single statement to the code fragment of Figure 1 (a) discards each new line character before it can become a problem for the next read. Again, this is only necessary when reading data of type "char."

while (true)
{
	cout << "A\tAdd\n";
	cout << "S\tSub\n";
	cout << "M\tMult\n";
	cout << "D\tDiv\n";
	cout << "E\tExit\n";

	cout << Operation: ";
	char operation;
	cin >> operation;
	cin.ignore();

	switch (operation)
	{
		.
		.
		.
	}
}
Discarding characters with ignore. Extraneous new line characters are deliberately discarded from the input stream with the ignore function.