std::basic_string::at in C++
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().
#include <stdexcept>
#include <iostream>
int main()
{
std::string str = "abc" ;
std::cout << "string size = " << str.size() << '\n' ;
try
{
str.at(4) = 't' ;
}
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)
Last Updated :
19 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...