Designing I/O

  1. Immediately before cin is used to input data from the keyboard, the program should always prompt the user to enter the proper data. For example,

    cout << "Enter the number of candy bars in a package\n";
    cout << "and the weight in ounces of one candy bar.\n";
    cout << "Then press return\n";
    cin >> number_of_bars;
    cin >> one_weight;

  2. Should always end the program with endl or \n.

  3. \n is an example of an escape sequence. It is a single non-printable character. Another useful escape sequence is \t, which represents a horizontal tab (usually 8 spaces). In general the backslash \ tells the compiler to interpret the next character differently.

    Other escape sequences are:
    \a alert
    \\ a single backslash
    \" a double quote

  4. Formatting numbers with a decimal point for output
    • The output stream cout has member functions that allows one to control the output format of numbers with decimal points (floats and doubles)
    • Example:
      Using the code:
      cout.setf(ios::fixed); // always uses fixed point rather than scientific notation
      cout.setf(ios::showpoint); // always shows a decimal point
      cout.precision(5); // shows exactly 5 decimal places with rounding;
      //the output of a number such as 3.14159625358979 will appear as 3.14160