at [C++ Reference]
Keywords: string,at
Date: 2009-10-10T19:35:57-0700

[[at]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- cz
- de
- es
- fr
- it
- jp
- nl
- pl
- ro
- ru
- sk
- tr
- tw

## 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

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •