Some Common Pitfalls

 

A common mistake for many new C++ programmers is to reverse the << and >> operators. A good way to remember which operator to use is to think of them as arrows. You always want the arrow to point to where you want the data to go. During input, you want the data to go into the variable, so the >> operator is used. During output, you want the data to go from the variable to the console, so the << operator is used.

Another common pitfall that most new C++ programmers encounter occurs when they try to read a line of text into a string variable. The following approach does not work when the line entered contains spaces, since the cin object is looking for white space to terminate the input.

1: 2: 3: 4: // Wrong way to read in an entire linestring line;cin >> line;cout << line;
Listing 7 Wrong way to input a line