1.6.1. Exercises: Input and Output

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

  1. Using Example 1.4, 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.11.

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

  2. Consider Example 1.5:

    Example 1.5. src/early-examples/fac2.cpp

    
    #include <iostream> 
    
    long factorial(long n) {
        long ans = 1;
        for (long i = 2; i <= n; ++i) {
            ans = ans * i;
            if (ans < 0) {
                return -1;
            }
        }
        return ans;
    }
    
    int main() {
        using namespace std;
        cout << "Please enter n: " << flush;
        long n;        1
        cin >> n;      2 
    
        if (n >= 0) { 
            long nfact = factorial(n);
            if (nfact < 0) {
                cerr << "overflow error: " 
                     << n << " is too big." << endl;
            }
            else {
                cout << "factorial(" << n << ") = "
                     << nfact << endl;
            }
        }
        else {
            cerr << "Undefined:  "
                 << "factorial of a negative number: " << n << endl;
        }
        return 0;
    }
    
    

    1

    long int

    2

    read from stdin, try to convert to long

    • Test Example 1.5 with a variety of input values, including some non-numeric values.

    • Determine the largest input value that will produce a valid output.

    • Can you change the program so that it will produce valid results for larger input values?

    • Modify the program so that it cannot produce invalid results.

    • Explore the effects of using the statement

       if (cin >> n)   {  ...  } 

      to enclose the processing of n in this program. In particular, try entering non-numeric data after the prompt. This is an example of the use of a conversion operator, which we discuss in more detail in Section 2.12.

    • Modify the program so that it will accept values from the user until the value 9999 is entered.