at

Syntax:

    #include <string>
    Char& at( size_type loc );
    const Char& at( size_type loc ) const;

The at() function returns the character in the string at index loc. The at() function is safer than the [] operator, because it won't let you reference items past the end of the string.

For example, consider the following code:

   string s("abcdef");
   for( int i = 0; i < 10; i++ ) {
     cout << "Element " << i << " is " << s[i] << endl;
   }

This code overruns the end of the string, producing potentially dangerous results. The following code would be much safer:

   string s("abcdef");
   for( int i = 0; i < 10; i++ ) {
     cout << "Element " << i << " is " << s.at(i) << endl;
   }

Instead of attempting to read garbage values from memory, the at() function will realize that it is about to overrun the string and will throw an exception.

Related Topics: [] operator