public member function
<string>

std::string::at

      char& at (size_t pos);
const char& at (size_t pos) const;
Get character in string
Returns a reference to the character at position pos in the string.

The function automatically checks whether pos is the valid position of a character in the string (i.e., whether pos is less than the string length), throwing an out_of_range exception if it is not.

Parameters

pos
Value with the position of a character within the string.
Note: The first character in a string is denoted by a value of 0 (not 1).
If it is not the position of a character, an out_of_range exception is thrown.
size_t is an unsigned integral type.

Return value

The character at the specified position in the string.

If the string object is const-qualified, the function returns a const char&. Otherwise, it returns a char&.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
// string::at
#include <iostream>
#include <string>

int main ()
{
  std::string str ("Test string");
  for (unsigned i=0; i<str.length(); ++i)
  {
    std::cout << str.at(i);
  }
  return 0;
}


This code prints out the content of a string character by character using the at member function:
Test string

Complexity

Unspecified.

Iterator validity

Generally, no changes.
On some implementations, the non-const version may invalidate all iterators, pointers and references on the first access to string characters after the object has been constructed or modified.

Data races

The object is accessed, and in some implementations, the non-const version modifies it on the first access to string characters after the object has been constructed or modified.
The reference returned can be used to access or modify characters.

Complexity

Constant.

Iterator validity

No changes.

Data races

The object is accessed (neither the const nor the non-const versions modify it).
The reference returned can be used to access or modify characters. Concurrently accessing or modifying different characters is safe.

Exception safety

Strong guarantee: if an exception is thrown, there are no changes in the string.

If pos is not less than the string length, an out_of_range exception is thrown.

See also