Use string subscript out of range with string member function "at" - C++ STL

C++ examples for STL:string

Description

Use string subscript out of range with string member function "at"

Demo Code

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

int main() /*w ww.j av  a 2s . co m*/
{ 
    string s1( "happy" ); 
    string s2( " birthday" ); 
    string s3; 

   // Use string copy constructor 
   string s4( s1 ); 
   
   try 
   { 
       cout << "Attempt to assign 'd' to s1.at( 30 ) yields:" << endl; 
       s1.at( 30 ) = 'd'; // ERROR: subscript out of range 
   }
   catch ( out_of_range &ex ) 
   { 
       cout << "An exception occurred: " << ex.what() << endl; 
   }
}

Result


Related Tutorials