Misc C++ Features

  1. Output formatting
    1. iomanip library is useful for manipulating output
      1. setw(width) function used to output text in a fixed number of characters
      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) << "goodbye" << endl;
        
        Output:
            You
            say
        goodbye
        
      3. std::left changes the alignment to the left
        // Make left justified
        cout << left;
        cout << setw(7) << "I" << setw(7) << "say" << setw(7) << "hello";
        
        Output:
        I      say    hello
        
    2. Controlling decimal number output
      1. std::fixed makes all floating-point numbers display their decimal points (no scientific notation)
      2. std::setprecision(places) rounds numbers to the specified number decimal places
      3. Example:
        double a = 1234567.159;
        cout << a << endl;    // 1.23457e+006
        
        cout << fixed;
        cout << a << endl;    // 1234567.159000
        
        cout << setprecision(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;