Inside Strings with the for
Loop
The for
loop provides a direct way to access each character in a string in turn. For example, Listing 5.6 enables you to enter a string and then displays the string character-by-character, in reverse order. You could use either a string
class object or an array of char
in this example because both allow you to use array notation to access individual characters in a string; Listing 5.6 uses a string
class object. The string
class size()
method yields the number of characters in the string; the loop uses that value in its initializing expression to set i
to the index of the last character in the string, not counting the null character. To count backward, the program uses the decrement operator (--
) to decrease the ...
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.