3.2.2 The Util Library

In this example, you are going to have an opportunity to explore the CodeHS utilities library. To access this library, you will include util.h in your file.

Basic Functionality

The util library helps with some basic functionality and setup. Since it uses the iostream library and the std namespace, these no longer need to be called out in your program.

The other basic functionality that is handled in the util library is user input. Using the readLine, readInt, and readDouble prompts, you can now create a variable, prompt the user, and read a value all in one line. The int and double prompts also have the ability to ask for a value in a specific range and provide a re-prompt option in case the prompt is not answered correctly the first time.

String Utilities

The util library has a few basic string utilities for common functions. First, there is a splitLine function that will split based on a space by default, but can split based on a character as well. Note that this has to be a character, so make sure you are always passing it a char in single quotes, for example ','.

In addition to the splitLine function, you will find two case functions, toUpperCase and toLowerCase. Both take a string and convert it to the specified case.

Random Function

Finally, you will find a random function. This function can either be called with no parameters or the user can specify a min and max value, inclusively.

The random function also has a setSeed function that takes an integer. Since random numbers are not truly random, but require a seed, the util library gives you the option to set the seed so that the random numbers can be generated in a repeatable manner.

Error Function

As mentioned earlier in the course, many errors in C++ do not end the program, but what if you want the program to end on an error? This may be the case in some situations where an error could cause an unrecoverable issue.

To use this function, just call it and pass a message. When the Error function executes, it will print the error to the screen and terminate the program.

This Example

Play around with some of the functionality of the util library. It should be relatively self-explanatory, especially when looking at the examples for help.

Last updated