当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ std::basic_string::at用法及代码示例


返回对指定位置pos处字符的引用。该函数自动检查pos是否是字符串中字符的有效位置(即pos是否小于字符串长度),如果不是,则抛出out_of_range异常。

用法:

reference at (size_type pos);
const_reference at (size_type pos) const;
参数:
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'; 
    } 
}

输出:


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


相关用法


注:本文由纯净天空筛选整理自 std::basic_string::at in C++。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。