Using a Subscript for Random Access
In the previous example we advanced our subscript one position at a time to capitalize each character in sequence. We can also calculate an subscript and directly fetch the indicated character. There is no need to access characters in sequence.
As an example, let’s assume we have a number between 0 and 15 and we want to generate the hexadecimal representation of that number. We can do so using a string that is initialized to hold the 16 hexadecimal “digits”:
- const string hexdigits = "0123456789ABCDEF";
- cout << "Enter a series of numbers between 0 and 15"
- << " separated by spaces. Hit ENTER when finished: "
- << endl;
- string result;
- string::size_type n;
- while (cin >> n)
- if (n < hexdigits.size())
- result += hexdigits[n];
- cout << "Your hex number is: " << result << endl;
If we give this program the input
- 12 0 5 15 8 15
the output will be
- Your hex number is: C05F8F
We start by initializing hexdigits to hold the hexadecimal digits 0 through F. We make that string const (§ 2.4, p. 59) because we do not want these values to change. Inside the loop we use the input value n to subscript hexdigits. The value of hexdigits[n] is the char that appears at position n in hexdigits. For example, if n is 15, then the result is F; if it’s 12, the result is C; and so on. We append that digit to result,whichwe print once we have read all the input.
Whenever we use a subscript, we should think about how we know that it is in range. In this program, our subscript, n, is a string::size_type, which aswe know is an unsigned type. As a result, we know that n is guaranteed to be greater than or equal to 0. Before we use n to subscript hexdigits, we verify that it is less than the size of hexdigits.
EXERCISES SECTION 3.2.3
Exercise 3.6: Use a range for to change all the characters in a string to X.
Exercise 3.7: What would happen if you define the loop control variable in the previous exercise as type char Predict the results and then change your program to use a char to see if you were right.
Exercise 3.8: Rewrite the program in the first exercise, first using a while and again using a traditional for loop. Which of the three approaches do you prefer and why
Exercise 3.9: What does the following program do Is it valid If not, why not
- string s;
- cout << s[0] << endl;
Exercise 3.10: Write a programthat reads a string of characters including punctuation and writes what was read but with the punctuation removed.
Exercise 3.11: Is the following range for legal If so, what is the type of c
- const string s = "Keep out!";
- for (auto &c : s) { }