Program Notes

The while condition in Listing 5.13 looks like this:

while (name[i] != '')

It tests whether a particular character in the array is the null character. For this test to eventually succeed, the loop body needs to change the value of i. It does so by incrementing i at the end of the loop body. Omitting this step keeps the loop stuck on the same array element, printing the character and its code until you manage to kill the program. Getting such an infinite loop is one of the most common problems with loops. Often you can cause it when you forget to update some value within the loop body.

You can rewrite the while line this way:

while (name[i])

With this change, the program works just as it did before. That’s because when name[i] is an ordinary character, its value is the character code, which is nonzero, or true. But when name[i] is the null character, its character-code value is 0, or false. This notation is more concise (and more commonly used) but less clear than what Listing 5.13 uses. Dumb compilers might produce faster code for the second version, but smart compilers produce the same code for both.

To print the ASCII code for a character, the program uses a type cast to convert name[i] to an integer type. Then cout prints the value as an integer rather than interpret it as a character code.

Unlike a C-style string, a string class object doesn’t use a null character to identify the end of a string, so you can’t convert Listing 5.13 to a string class version merely by replacing the array of char with a string object. Chapter 16 discusses techniques you can use with a string object to identify the last character.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.188.244