The C++ data(), length(), strlen() and c_str() 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++ basic_string member functions: data(), length(), strlen() and c_str() in C++ programming
To show: How to use the C++ basic_string class member functions: data(), length(), strlen() and c_str() in C++ programming
// the C++ data(), length(), strlen() and c_str() program example
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
string str1("Testing the data()");
cout<<"str1 string object is: "<<str1<<endl;
cout<<"Operation: str1.length()"<<endl;
cout<<"The length of str1 = "<<unsigned int(str1.length())<<endl<<endl;
// converting a string to an array of characters
const char *ptr1 = 0;
ptr1= str1.data();
cout<<"Operation: str1.data()"<<endl;
cout<<"The modified ptr1 string object is: "<<ptr1<<endl;
cout<<"Operation: strlen(ptr1)"<<endl;
cout<<"The length of character array str1 = "<<unsigned int(strlen(ptr1))<<endl<<endl;
// converting a string to a C-style string
const char *cstr1 = str1.c_str();
cout<<"Operation: str1.c_str()"<<endl;
cout<<"The C-style string c_str1 is: "<<cstr1<<endl;
cout<<"Operation: strlen(ptr1)"<<endl;
cout<<"The length of C-style string str1 = "<<unsigned int(strlen(cstr1))<<endl;
return 0;
}
Output example:
str1 string object is: Testing the data()
Operation: str1.length()
The length of str1 = 18
Operation: str1.data()
The modified ptr1 string object is: Testing the data()
Operation: strlen(ptr1)
The length of character array str1 = 18
Operation: str1.c_str()
The C-style string c_str1 is: Testing the data()
Operation: strlen(ptr1)
The length of C-style string str1 = 18
Press any key to continue . . .