1.4.1. Exercises: Standard Input and Output

[ fromfile: cppintro.xml id: x-inputoutput ]

  1. In the dist directory we have provided a tarball named src.tar.gz that contains all the code examples in this book. An extremely valuable practice that you should adopt is to take each code example, build and run it to see how it is supposed to behave, and then break it by making various changes to see what happens. Sometimes you can learn how the compiler responds to a particular syntax error that your change produced. The compiler can be your best friend if you can learn to understand its language. Other times you can see how the runtime behavior of the program is affected by a particular logic error that you produced. In each case, the experience can strengthen your understanding of C++ programming.

  2. Using Example 1.2, do the following experiments:

    • First, compile and run it, to see its normal behavior.

    • What happens if you enter a non-numeric value for the birth year?

    • What happens if you enter a name like Curious George as your name?

    • What happens if you remove the following line?

      using namespace std; 

    • Replace the statement

       cin >> yourName; 

      with the statement

       getline(cin, yourName); 

      and try Curious George again.

    • Can you explain the differences in behavior between cin >> and getline()? We discuss this in Section 1.8.

    • Add some more questions to the program that require a variety of numerical and string answers and test the results.