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!”
Start up a decent text editor (e.g., VS Code) and use it to create a file named
hello.cpp, containing the following code.TipYou 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
#includedirective on line 1 provides access to the C++ I/O library. - 2
-
The object
couton line 7 is an output stream (ostream) object representing console output. The<<is the stream insertion operator, responsible for inserting values into the stream. Theendlis 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
coutasstd::coutandendlasstd::endl. Features of the C++ standard library are defined inside a namespace calledstdand must be referenced using thestd::prefix unless you instruct the compiler to use all names from that namespace without that prefix.
Open a terminal window and cd to the directory where you saved
hello.cpp, then enter the following command:g++ hello.cpp -o helloEnter
./helloto run the program.The
g++command invokes the GNU C++ compiler. This belongs to the same family of compilers asgcc, the GNU C compiler, and it therefore supports a very similar range of command line options. For example, you use-cif 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.
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
fstreamgives us access to classes that can read from or write to files. - 2
-
Including
vectorallows 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 holdingfloatvalues 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
argcandargvparameters ofmain()serve the same purpose in C++ that they do in C: that of conveying command line arguments to the program. - 5
-
The vector
datacan holdfloatvalues but is initially empty.
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.
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
ifstreamobject,ifstreambeing one of the classes in the C++ IOStreams library. The first line of this code fragment creates such an object. Notice how anifstatement is used to check the status of this object after creation. If the object evaluates tofalseinside anifstatement 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.
After the line that creates the empty vector, add code to call the
read_datafunction: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_datafunction:float value; while (input >> value) { data.push_back(value); }Here,
inputanddataare the function parameters:inputis an input stream passed to the function, anddatais the vector offloatvalues that will receive data read from the input stream.Notice the syntax used here.
input >> valuereads a single numeric value into the variable namedvalue. When this is used as part of awhileloop, 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 fileNoteYou should use one of the methods of
vectorhere—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 namedmean_value. It should accept afloatvector as its sole parameter and should return the arithmetic mean of the values in that vector to the caller.NoteApproach writing this function exactly as you would approach writing it in C, but make sure you use a
constreference as a parameter, so that the function is as efficient as possible.Check that your program compiles before proceeding.
Finally, add code to
mainthat 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.