Game Development Reference
In-Depth Information
We can also alter the way decimal numbers are represented by outputting them as hexadecimal
values, octal values, or back to decimal values. We can also use the showbase and noshowbase
to include or remove the 0x appendage on hexadecimal numbers or the 0 appendage on octal
numbers.
The last operation shown with the stringstream is to obtain a string representation of the data
we have created. This is necessary, as we cannot use a stringstream object as an input to cout .
The str method is provided by the stringstream class for this purpose.
Summary
This chapter has given you an introduction to the STL string library. This is the first time you have
had to consider how C++ uses templates to specialize generic code into specific implementations.
This process is used throughout the STL and the string class is a perfect introduction to this
concept. You've used strings in the examples contained in this topic from the very beginning, which
goes to show the flexibility and power of the ability of C++ ability to have generic code be hidden
from programmers. Understanding how templates can be used in such a manner will give you an
advantage over many programmers, as there are many who believe templates are too complex to be
used in day-to-day code.
You've seen in this chapter how you can access and manipulate string data in C++ programs using
the methods provided by STL rather than using the older C-style string methods. This can lead to
your code being more robust, as the string class is a first class type in C++. As you've seen, C-style
strings are nothing more than arrays that end with a null terminator and rely on convention to ensure
that they are implemented properly. The string class avoids this problem by enforcing the proper
null termination of strings without requiring the user to remember to accommodate them.
Another advantage to C++ strings is that the storage for string data is automatically handled by the
class. When appending C-style strings, you would be responsible for allocating new arrays large
enough to hold both strings and ensuring that the data are copied properly, deleted properly, and
null terminated properly. This can lead to length functions when a single line of C++ code can carry
out the same operation. Thanks to the nature of C++ and the STL we do not need to look at memory
management topics until much later in this topic.
You've also seen in this chapter that STL containers can be accessed through iterators. This is a
common design pattern in C++ and all STL containers use the same access method. You will see
this in action throughout the rest of this topic, including in the next chapter, where we look at the
STL array and vector containers.
 
Search WWH ::




Custom Search