Bullet Proof Data Entry: In-Memory Formatting & Conversion

PAGE UNDER CONSTRUCTION

In a C++ program, all data have a type, which determines how much memory must be allocated to store the data and how the computer should interpret the pattern of 1's and 0's comprising the data. In chapter 2, we learned that it is possible to change data from one type to another with the casting operator. (It's important to recall that the casting operator doesn't change the data itself; instead, casting creates an expression that represents, as closely as possible, the same data but in a different type.) However, it's only possible to cast data between two types when the types are similar or "sort of the same." For example, an integer and a double are similar or "sort of the same" in the sense that both are numbers, just different kinds of numbers.

Unfortunately, strings (i.e., instances of the string class or C-strings) are not similar or the same as numbers. As we learned in chapter 8, it is possible to convert numbers to C-strings (Converting Numbers To C-Strings), numbers to string objects (Converting numbers To Strings), and strings (both kinds) to numbers (Bulletproof Code: Strings → Numbers). But these conversions required specialized functions that go beyond the capabilities of the casting operator.

One of the problems that we have faced throughout our study of C++ is how to enter data in a robust or "bulletproof" way. That is, if the user enters the wrong kind or type of data, the program might chrash or fail in other ways. What we need is some way of entering the data, testing it to make sure it is appropriate, and then using the validated data to complete the program operations. As all data can be represented as a string, a common solution is to read all into a string variable, validate that it meets some appropriate criteria, and then convert the string to its finall type. The functions covered in chapter 8 are sufficient for simple data, but more complex or more structured data require a different approach.