The C++ at() member function program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using the C++ at() member function which return a reference to the element at a specified location in the string in C++ programming
To show: How to use the C++ at() member function to return a reference to the element at a specified location in the string in C++ programming
// the C++ at() program example
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
string str1("Operation"), str2("Desert Storm");
const string constr1("Making cakes"), constr2("Start eating");
cout<<"str1 string is: "<<str1<<endl;
cout<<"str2 string is: "<<str2<<endl;
cout<<"constr1, const string is: "<<constr1<<endl;
cout<<"constr2, const string is: "<<constr2<<endl;
// element access of the non const strings
basic_string <char>::reference RefStr1 = str1[4];
basic_string <char>::reference RefStr2 = str2.at(7);
// index starts from 0 lor!
cout<<"\n---str1[5]---"<<endl;
cout<<"The 5th character of str1 is: "<<RefStr1<<endl<<endl;
cout<<"---str2.at(7)---"<<endl;
cout<<"The 7th character of str2 is: "<<RefStr2<<endl<<endl;
// element access to the const strings
basic_string <char>::const_reference cRefStr1 = constr1[constr1.length()];
basic_string <char>::const_reference cRefStr2 = constr2.at(8);
cout<<"---constr1.length()---"<<endl;
cout<<"The length of the constr1 string is: "<<unsigned int(constr1.length())<<endl;
cout<<"\nTesting the null character..."<<endl;
cout<<"---cRefStr1 = constr1[constr1.length()]---"<<endl;
cout<<"Operation: (cRefStr1 == \'\\0\')"<<endl;
if(cRefStr1 == '\0')
cout<<"The null character is returned."<<endl;
else
cout<<"The null character is not returned."<<endl;
cout<<"\n---constr2.at(8)---"<<endl;
cout<<"The 8th character of the constr2 is: "<<cRefStr2<<endl;
return 0;
}
Output example:
str1 string is: Operation
str2 string is: Desert Storm
constr1, const string is: Making cakes
constr2, const string is: Start eating
---str1[5]---
The 5th character of str1 is: a
---str2.at(7)---
The 7th character of str2 is: S
---constr1.length()---
The length of the constr1 string is: 12
Testing the null character...
---cRefStr1 = constr1[constr1.length()]---
Operation: (cRefStr1 == '\0')
The null character is returned.
---constr2.at(8)---
The 8th character of the constr2 is: t
Press any key to continue . . .