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 array subscript by one in each loop. Also Listing 5.6 uses the greater-than-or-equal-to relational operator (>=) to test whether the loop has reached the first element. We’ll summarize all the relational operators soon.

Listing 5.6. forstr1.cpp


// forstr1.cpp -- using for with a string
#include <iostream>
#include <string>
int main()
{
    using namespace std;
    cout << "Enter a word: ";
    string word;
    cin >> word;

    // display letters in reverse order
    for (int i = word.size() - 1; i >= 0; i--)
        cout << word[i];
    cout << " Bye. ";
    return 0;
}


Here is a sample run of the program in Listing 5.6:

Enter a word: animal
lamina
Bye.

Yes, the program succeeds in printing animal backward; choosing animal as a test word more clearly illustrates the effect of this program than choosing, say, a palindrome such as rotator, redder, or stats.

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

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