5. Introduction to C++

This short worksheet introduces you to the C++ language, building directly on what you learned about C programming last semester. You will need to use C++ for some of your practical work in Level 2.

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 introductory video by Derek Banas to be useful.

5.1. Compiling “Hello World!”

  1. Start up a decent text editor (e.g., Atom) and use it to create a file called hello.cpp, containing the following:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
      cout << "Hello World!" << endl;
      return 0;
    }
    

    Compare this with what the same program would look like if written in C. Note the different #include directive on line 1, needed here because C++ has a very different I/O library. You can see just how different it is on line 7. Here, cout 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 in the terminal window.

    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 their prefixes.

  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
    

    Run the program with ./hello.

    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.

5.2. 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. The program will compute the mean value of numeric data stored in a file.

  1. Start by downloading mean.cpp. This file contains the following skeletal program:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    #include <iostream>
    #include <fstream>
    #include <vector>
    
    using namespace std;
    
    void read_data(istream& input, vector<float>& data)
    {
    }
    
    int main(int argc, char* argv[])
    {
      if (argc != 2) {
        cerr << "Usage: ./mean <filename>" << endl;
        return 1;
      }
    
      vector<float> data;
    
      return 0;
    }
    

    Compile and run this program. It should compile and run successfully, prompting for a filename as a command line argument. In its current state, it does nothing if the command line argument is provided.

  2. 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. Notice how an if statement is used to check the status of this object after creation.

    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.

  3. 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.

  4. 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 float vector 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.

  5. 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
    

    Tip: you’ll need to 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.

  6. 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, to ensure that the function is as efficient as possible.

    Check that your program compiles before proceeding.

  7. 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