Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

std::basic_string::at in C++

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Returns a reference to the character at the specified location pos. 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.

Syntax:

reference at (size_type pos);
const_reference at (size_type pos) const;
Parameters :
pos - position of the character to return
Return value :
Reference to the requested character
Exceptions :
Throws std::out_of_range if pos >= size().




// CPP program to access a character through
// std::basic_string::at 
#include <stdexcept>
#include <iostream>
  
int main()
{
    // String with valid indices from 0 to 2
    std::string str = "abc";
  
    // Printing size of string
    std::cout << "string size = " << str.size() << '\n';
  
    // Accessing out of bounds index
    try 
    {
        str.at(4) = 't';
    }
      
    // If error is generated, it is caught
    catch (std::out_of_range const& error) 
    {
        std::cout << error.what() << '\n';
    }
}

Output:

string size = 3
basic_string::at: __n (which is 4) >= this->size() (which is 3)

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Last Updated : 07 Jul, 2017
Like Article
Save Article
Similar Reads
Related Tutorials