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.
Start up a decent text editor (e.g., VS Code) and use it to create a file
named hello.cpp
, containing the following:
1#include <iostream>
2
3using namespace std;
4
5int main()
6{
7 cout << "Hello World!" << endl;
8 return 0;
9}
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.
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.
In this exercise, you will write a more substantial program that does file I/O and uses a vector for data storage.
Start by downloading mean.cpp
. This file contains the
following skeletal program:
1#include <iostream>
2#include <fstream>
3#include <vector>
4
5using namespace std;
6
7void read_data(istream& input, vector<float>& data)
8{
9}
10
11int main(int argc, char* argv[])
12{
13 if (argc != 2) {
14 cerr << "Usage: ./mean <filename>" << endl;
15 return 1;
16 }
17
18 vector<float> data;
19
20 return 0;
21}
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.
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.
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.
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.
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.
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.
Check that your program compiles before proceeding.
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
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.