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) |
![]() |
(b) |
![]() |
(c) |
![]() |
(d) |
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) { . . . } }