Misc C++ Features

  1. Output formatting
    1. iomanip library is useful for manipulating output
      1. setw(width) function used to output text in fixed columns
      2. Example:
        // Put this with other include statements
        #include <iomanip>
        
        // Output each literal in a column of 7 spaces right justified
        cout << setw(7) << "You" << endl;
        cout << setw(7) << "say" << endl;
        cout << setw(7) << "hello" << endl;
        
        Output:
            You
            say
          hello
        
    2. Controlling decimal number output
      1. cout.setf(ios::fixed) makes all floating-point numbers display their decimal points (no scientific notation)
      2. cout.precision(places) rounds the decimal places to a given number
      3. Example:
        double a = 1234567.159;
        cout << a << endl;    // 1.23457e+006
        
        cout.setf(ios::fixed);
        cout << a << endl;    // 1234567.159000
        
        cout.precision(2);
        cout << a << endl;    // 1234567.16
        
  2. Constants
    1. Variables whose values cannot be modified
    2. Can make program easier to read and modify in the future
    3. Use const before declaration and always assign a value
      // Correct
      const double PI = 3.14;
      
      // Wrong!
      const double PI;
      PI = 3.14;
      
      // Using a constant
      area = PI * radius * radius;
      
    4. Best practice is to use ALL CAPS for constants
  3. Special assignment operators

    Example Equivalent
    x++; x = x + 1;
    x--; x = x - 1;
    x += 2; x = x + 2;
    x -= 2; x = x - 2;
    x *= 2; x = x * 2;
    x /= 2; x = x / 2;
    x %= 2; x = x % 2;