Trap 5 - The cin Operator

◀ Trap 4 - Decimal Number▶ Trap 6 - Prime Number
Amazon The input stream operator, cin, is perhaps one of the most often used operators in C++. Knowing the exact behavior of it is important! What does the following program do? Describe its behavior in plain English.
#include <iostream>
using namespace std;

int main(){
	char c;
	int counter = 0;
	cout << "Enter anything up until you enter a newline: ";
	cin >> c;
	while(c!='\n') {
		counter++;
		cin >> c;
} cout << "You entered " << counter << " characters.\n"; return 0; }

Solution
At first it appears to count the number of characters the user has entered until a newline is entered, but this is not correct! If you run the program, you will realize that the program never terminates!

Remember, cin ignores white spaces, which include spaces, tabs, and newlines.
Therefore, c can never be a newline and the while loop never terminates.


From this exercise you should learn that knowing only the superficial behavior of a C++ function never suffices; you need to go deeper and explore any exceptions associated with it.

In this case, you know that cin receives inputs from the user, but you may not know that there are exceptions to that behavior: It ignores white spaces.

Whenever you use a function provided by C++ standard library, make sure you know what exactly it does, either by experimenting or looking it up online.

Next let’s look at an example of traps that are involved in writing a function!

◀ Trap 4 - Decimal Number▶ Trap 6 - Prime Number

fShare
Questions? Let me know!