Introduction to C++

This exercise gives you some practice at writing C++ code and invoking the compiler. We assume use of the the SoCS Linux machines, but instructions given here should also work without changes on any Linux system (including one installed via Windows Subsystem For Linux), or on Macs with a suitable compiler (e.g., the Xcode Command Line Tools).

Compiling “Hello World!”

  1. Start up a decent text editor (e.g., VS Code) and use it to create a file named hello.cpp, containing the following code.

    Tip

    You can use the ‘Copy to Clipboard’ button that appears in the top-right of the code panel to help with this, but we recommend you actually type in the code, as this will help you acclimatize more rapidly to C++ features and syntax.

    1#include <iostream>
    
    3using namespace std;
    
    int main()
    {
    2  cout << "Hello World!" << endl;
    
      return 0;
    }
    1
    The #include directive on line 1 provides access to the C++ I/O library.
    2
    The object cout on line 7 is an output stream (ostream) object representing console output. The << is the stream insertion operator, responsible for inserting values into the stream. The endl is a stream manipulator that inserts a carriage return character into the output stream and then flushes the buffer to ensure that output appears immediately in the terminal window.
    3
    Line 3 isn’t strictly necessary, but without it, you would have to refer to cout as std::cout and endl as std::endl. Features of the C++ standard library are defined inside a namespace called std and must be referenced using the std:: prefix unless you instruct the compiler to use all names from that namespace without that prefix.
  2. Open a terminal window and cd to the directory where you saved hello.cpp, then enter the following command:

    g++ hello.cpp -o hello

    Enter ./hello to run the program.

    The g++ command invokes the GNU C++ compiler. This belongs to the same family of compilers as gcc, the GNU C compiler, and it therefore supports a very similar range of command line options. For example, you use -c if you want to the compiler to generate a file of object code rather than creating an executable program.

A More Substantial Program

In this exercise, you will write a more substantial program that does file I/O and uses a vector for data storage.

  1. Start by copying the following skeletal program into a text editor, then save the code as a file named mean.cpp. (You can use the ‘Copy to Clipboard’ button at the top-right of the code panel to help with this, though we recommend actually typing it in.)

    #include <iostream>
    1#include <fstream>
    2#include <vector>
    
    using namespace std;
    
    3void read_data(istream& input, vector<float>& data)
    {
    }
    
    4int main(int argc, char* argv[])
    {
      if (argc != 2) {
        cerr << "Usage: ./mean <filename>" << endl;
        return 1;
      }
    
    5  vector<float> data;
    
      return 0;
    }
    1
    Including fstream gives us access to classes that can read from or write to files.
    2
    Including vector allows us to create vectors: dynamic arrays of any type of data we choose.
    3
    The read_data() function requires that we supply an input stream and a vector capable of holding float values as arguments. Both parameters are references (signified by the &) because both the input stream and the vector will be changed by what happens inside this function.
    4
    The argc and argv parameters of main() serve the same purpose in C++ that they do in C: that of conveying command line arguments to the program.
    5
    The vector data can hold float values but is initially empty.
  2. Compile and run this program. It should compile and run successfully, displaying a usage message if you fail to provide a command line argument, and doing nothing at all if a command line argument is provided.

  3. Before line 18 of mean.cpp, add code that opens the file named on the command line for reading:

    ifstream infile(argv[1]);
    if (not infile) {
      cerr << "Error: cannot access " << argv[1] << endl;
      return 2;
    }

    Reading from a file in C++ involves the use of an ifstream object, ifstream being one of the classes in the C++ IOStreams library. The first line of this code fragment creates such an object. Notice how an if statement is used to check the status of this object after creation. If the object evaluates to false inside an if statement then the attempt to open the file failed.

    Check that the program still compiles and runs. When running, try using the name of a non-existent file as the command line argument. You should see the error message displayed. Then try using the name of a file that does exist. This time, there should be no error.

  4. After the line that creates the empty vector, add code to call the read_data function:

    read_data(infile, data);

    Check that the program still compiles and that its run-time behaviour is unchanged.

  5. The program doesn’t actually read anything from a file yet. Fix that now by adding the following code to the currently empty read_data function:

    float value;
    while (input >> value) {
      data.push_back(value);
    }

    Here, input and data are the function parameters: input is an input stream passed to the function, and data is the vector of float values that will receive data read from the input stream.

    Notice the syntax used here. input >> value reads a single numeric value into the variable named value. When this is used as part of a while loop, the operation will be executed repeatedly until it fails—e.g., because the end of the file has been reached. Within the body of the loop, all we do have to do is put the value onto the end of the given vector.

    After adding this code, check that the program still compiles, but don’t bother running it just yet.

  6. Create a small file containing 4 or 5 numeric values, one per line. Then add a line to your program, after the call to read_data, that displays the number of values read from the file into the vector—e.g., like this:

    4 values read from file
    Note

    You should use one of the methods of vector here—see the Introduction to C++ lecture and examples.

    Then try running the program on your sample data file to see whether it has read all the values successfully.

  7. Now add a new function definition to the file, before main. This new function should be named mean_value. It should accept a float vector as its sole parameter and should return the arithmetic mean of the values in that vector to the caller.

    Note

    Approach writing this function exactly as you would approach writing it in C, but make sure you use a const reference as a parameter, so that the function is as efficient as possible.

    Check that your program compiles before proceeding.

  8. Finally, add code to main that calls your function and displays the returned value. When run on a suitable data file, the final program output should look something like this:

    4 values read from file
    Mean value = 3.9125

Learning More

For more information on C++ programming, please see the links provided in the Introduction to C++ lecture. In particular, you may find the cplusplus.com tutorial and the video by Derek Banas to be useful.