0

In C++, what is the difference between the string.at(i) method and string[i]? What are the advantages or disadvantages to using one or the other?

#include <iostream>
#include <string>

int main() {
   std::string s = "Hello World";
   std::cout << s.at(1) << endl;
   std::cout << s[1] << endl;
}

As far as I know, they do the same thing, but I don't know much about C++.

  • 1
    `std::string::at` throws if the index you pass is out of range (i.e. if it's `>= s.size()`); `std::string::operator[]` does not. – paolo Apr 10 '22 at 16:37

2 Answers2

3

std::string.at member function accesses the specified character with bounds checking while the std::string::operator[] accesses the specified character without bounds checking.

That is, with std::string::at, bounds checking is performed and exception of type std::out_of_range will be thrown on invalid access.

On the other hand, with std::string::operator[], no bounds checking is performed. If pos > size(), the behavior is undefined.

Jason
  • 36,170
  • 5
  • 26
  • 60
0

s.at() raises an out_of_range exception if we try to access a position which is out of allocated limits.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s = "ABCD";
    // cout << s[100] << endl; // No Exception Raised
    cout << s.at(100) << endl;  // Raises An Exception

    return 0;
}

enter image description here