Table of Contents

Make sure to also view the "C++ Quick Reference" part of this textbook for a reference guide on basic C++ syntax.

1. Includes

Include Features
#include <iostream> Use of cout (console output), cin (console input), getline
#include <string> Use of the string data type and its functions
#include <fstream> Use of ofstream (output file stream), ifstream (input file stream), and related functions
#include <array> Use of array from the Standard Template Library
#include <vector> Use of vector from the Standard Template Library
#include <cstdlib> C standard libraries, usually used for rand().
#include <ctime> C time libraries, usually used for srand( time( NULL ) ); to seed random # generator
#include <cmath> C math libraries, such as sqrt, trig functions, etc.
#include "file.h Use "" to include .h files within your own project. DON'T USE INCLUDE ON .cpp FILES!!
About the using command

The using namespace std; command states that we're using the std namespace. If this is left off, then we need to prefix any C++ types and functions with std::, such as std::cout << "Hello!" << std::endl;

Best practices:

  • If your program ONLY uses C++ standard library includes, use using namespace std; for brevity.
  • If your program uses MULTIPLE LIBRARIES, avoid using namespace std; and prefix each type/function with the library it belongs to (e.g., std::string from the STD library, sf::vector2f from the SFML library)

2. Bare minimum C++ programs

  • Without arguments:

    #include <iostream>
    using namespace std;
    
    int main()
    {
      cout << "Hello, world!" << endl;
      return 0;
    }
    
  • With arguments:

    #include <string>
    #include <iostream>
    using namespace std;
    
    int main( int argCount, char* args[] )
    {
      if ( argCount < 4 )
      {
        cout << "Not enough arguments!"
             << endl; return 1;
       }
    
      int my_int = stoi( args[1] );
      float my_float = stof( args[2] );
      string my_string = string( args[3] );
    
      return 0;
    }
    

3. Building and running from the command line

  • Building a single source file:

    g++ SOURCEFILE.cpp -o PROGRAMNAME.out
    
  • Building multiple source files:

    g++ *.cpp *.h -o PROGRAMNAME.out
    
  • Running a program without arguments:

    ./PROGRAMNAME.out
    
  • Running a program with arguments:

    ./PROGRAMNAME.out arg1 arg2 arg3
    

4. Variable declaration

  • Declaring a variable:

    DATATYPE VARIABLENAME;

  • Declaring a variable and assigning a value:

    DATATYPE VARIABLENAME = VALUE;

  • Declaring and assigning a named constant:

    const DATATYPE NAME = VALUE;

  • Assigning a new value to an existing variable:

    VARIABLENAME = VALUE;

  • Copying a value from one variable to another:

    UPDATEDVAR = COPYME;

  • Data types and values:
Data type Value examples
int -5, 0, 100
float 0.99, -3.25, 1.0
string "Hello world!"
char 'a', '$'
bool true, false
  • Increment/Decrement statements:
    • a++, a--
    • ++a, --a
    • a+=5;, a-=5;
    • a = a + 5;, a = a - 5;

Notes:

  • LHS = RHS; copies FROM RHS TO LHS; make sure you have the right order!
  • A hard-coded value, like "Hello", is known as a literal.

5. Console input and output

  • Output a variable's value:

    cout << VARIABLENAME;

  • Output a string literal:

    cout << "Hello";

  • Chain together multiple items:

    cout << "Label: " << VARIABLENAME << endl;

  • Input to a variable:

    cin >> VARIABLENAME;

  • Input a whole line to a string variable:

    getline( cin, STRINGVARIABLE );

Notes:

  • The << operator is called the output stream operator and is used on cout statements.
  • The >> operator is called the input stream operator and is used on cin statements.
  • endl is only to be used with cout statements, not cin!
  • getline can only be used with strings!! Use cin >> for other data types.
  • You need a cin.ignore() ONLY in between

    cin >> ... and

    getline( cin, ... ).

    • If your program is skipping an input then you're missing a cin.ignore();.
    • If your program is getting input but not storing the first letter then you have too many cin.ignore(); statements / they're in the wrong place.

6. Boolean expressions

  • AND (&&)
    • Expression is TRUE if all sub-expressions are TRUE
    • Expression is FALSE if at least one sub-expression is FALSE
a b a AND b
T T T
T F F
F T F
F F F
  • OR (||)
    • Expression is TRUE if at least one sub-expression is TRUE
    • Expression is FALSE if all sub-expressions are FALSE
a b a OR b
T T T
T F T
F T T
F F F
     
  • NOT (!)
    • Expression is TRUE if sub-expression is FALSE
    • Expression is FALSE if sub-expression is TRUE
a NOT a
T F
F T

7. If statements

IF STATEMENT:                  IF/ELSE STATEMENT:

if ( CONDITION_A )             if ( CONDITION_A )
{                              {
  // Action A                    // Action A
}                              }
                               else
                               {
                                 // Action Z
                               }


IF/ELSE IF STATEMENT:          IF/ELSE IF/ELSE STATEMENT:

if ( CONDITION_A )             if ( CONDITION_A )
{                              {
  // Action A                    // Action A
}                              }
else if ( CONDITION_B )        else if ( CONDITION_B )
{                              {
  // Action B                    // Action B
}                              }
else if ( CONDITION_C )        else if ( CONDITION_C )
{                              {
  // Action C                    // Action C
}                              }
                               else
                               {
                                 // Action Z
                               }
  • Condition types can be a boolean variable or a boolean expression:

    bool done = true;
    int a = 10, b = 5;
    if ( done ) // variable
    {
      cout << "Goodbye!" << endl;
    }
    if ( a > b ) // expression
    {
      cout << "a is bigger!" << endl;
    }
    
  • else statements NEVER TAKE A CONDITION
  • Whichever condition evaluates to true, all future else if and else statements are skipped.

8. Switch statements

switch( myNumber )
{
  case 1:
    cout << "It's one!" << endl;
    break;

  case 2:
    cout << "It's two!" << endl;
    break;

  default:
    cout << "I don't know what it is!" << endl;
}
  • You can leave off break; from a case statement. In this case, fallthrough occurs, where the following case's code will be executed, up until it hits a break; statement.
  • Switch statements like the one above can be replaced with "if myNumber equals 1" and "else if myNumber equals 2".
  • In C++, switch doesn't work with string, only primitive data types like int, float, char.
  • Fallthrough example:

    char choice;
    cout << "Enter a choice: (y/n): ";
    cin >> choice;
    
    switch( choice )
    {
      case 'y':
      case 'Y':
        cout << "YES" << endl;
        break;
    
      case 'n':
      case 'N':
        cout << "NO" << endl;
        break;
    
      default:
        cout << "INVALID INPUT!" << endl;
    }
    

9. While loops

while ( CONDITION ) { }

  • While loops use CONDITIONS like if statements do.
  • While loops are susceptible to infinite loop errors if nothing within the loop causes the CONDITION to evaluate to false eventually. Be careful!
  • Example:

    while ( a < b )
    {
      cout << a << endl;
      a++;
    }
    

10. For loops

Normal for loop: for ( INIT; CONDITION; UPDATE ) { }

  • Example:

    for ( int i = 0; i < 10; i++ )
    {
      cout << i << endl;
    }
    
  • When using STL arrays or vectors, size_t or unsigned int should be used instead of int for i. This will remove the warning relating to testing .size() (which returns size_t) against a signed integer.

Range-based for loop: for ( INIT : RANGE ) { }

  • In versions of C++ past C++98 (from 1998) you can use range-based for loops to iterate over a range of items:
  • Example:

    vector<int> myVec = { 1, 2, 3, 4 };
    for ( int element : myVec )
    {
      cout << element << endl;
    }
    

11. Arrays and vectors

  • Declare a C-style array:

    DATATYPE ARRAYNAME[ SIZE ];

  • Declare a C++ STL array:

    array<DATATYPE, SIZE> ARRAYNAME;

  • Declare a C++ STL vector:

    vector<DATATYPE> VECTORNAME;

  • Declare a dynamic array via pointer:

    DATATYPE * PTR = NEW DATATYPE[ SIZE ];

  • Destroy a dynamic array:

    delete [] PTR;

  • Initialize an array with an initializer list:

    DATATYPE ARRAY[] = { VAL1, VAL2, VAL3 }

    (also works for array and vector).

  • The position of an item within an array is called its index.
  • The variable within the array at some position is called its element.
  • A vector is a dynamic array, but you don't have to worry about the memory management. :) This means that it can be resized.
  • A array is a fixed size, just like the C-style array.
  • Example: Iterate over an array/vector

    // C-style array:
    for ( int i = 0; i < TOTAL_STUDENTS; i++ )
    {
      cout << "index: " << i << ", value: " << students[i] << endl;
    }
    
    // STL Array and STL Vector:
    for ( size_t i = 0; i < bankBalances.size(); i++ )
    {
      cout << "index: " << i << ", value: " << students[i] << endl;
    }
    

    (size_t is another name for an unsigned int, which allows values of 0 and above - no negatives.)


12. File I/O

  • #include <fstream> is required to use ifstream (input file stream) and ofstream (output file stream) types.
  • An ifstream open will fail if the file requested does not exist or cannot be found. Use if ( input.fail() ) to check for a failure scenario.
  • An ofstream open will create a file if it doesn't already exist.
  • The default path where files are written to or read from is wherever your project file is (.vcxproj for Visual Studio, .cbp for Code::Blocks). You can also set a default working directory in your project settings.
    • Mac users may need to specify an absolute path, like "~/myfile.txt", which will put the file in your home directory. I don't know how to use XCode but we can work through it together if you need help.
  • Example: Create an output file and write

    ofstream output;
    output.open( "file.txt" );
    
    // Write to text file
    output << "Hello, world!" << endl;
    
  • Example: Create an input file and read

    ifstream input;
    input.open( "file.txt" );
    if ( input.fail() )
    {
      cout << "ERROR: could not load file.txt!" << endl;
    }
    string buffer;
    
    // read a word
    input >> buffer;
    
    // read a line
    getline( input, buffer );
    

Author: RachelWil

Created: 2026-10-14 Wed 11:11

Validate