The C++ c_str(), length(), data() and strlen() 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++ basic_string member functions: c_str() to convert the contents of a string as a C-style, null-terminated, string, length() to return the current number of elements in a string, data() to convert the contents of a string into an array of characters and strlen() to return the C-style string length.

To show: How to use the C++ basic_string c_str(), length(), data() and strlen() member functions in C++ programming

 

// the C++ c_str(), length(), data() and strlen() program example

#include <string>

#include <iostream>

using namespace std;

 

int main(void)

{

string str1("Testing the c_str");

cout<<"The original string object str1 is: "<<str1<<endl;

cout<<"Operation: str1.length()"<<endl;

cout<<"The length of the string object str1 = "<<str1.length()<<endl<<endl;

 

// a string to an array of characters conversion

const char *ptr1 = 0;

ptr1= str1.data();

cout<<"Operation: ptr1= str1.data()"<<endl;

cout<<"The string object pointed by ptr1 is: "<<ptr1<<endl;

cout<<"\nOperation: strlen(ptr1)"<<endl;

cout<<"The length of character array str1 = "<<strlen(ptr1)<<endl<<endl;

 

// a string to a C-style string conversion

const char *cstr1 = str1.c_str();

cout<<"Operation: *cstr1 = str1.c_str()"<<endl;

cout<<"The C-style string c_str1 is: "<<cstr1<<endl;

cout<<"\nOperation: strlen(cstr1)"<<endl;

cout<<"The length of C-style string str1 = "<<strlen(cstr1)<<endl;

 

return 0;

}

 

Output example:

 

The original string object str1 is: Testing the c_str

Operation: str1.length()

The length of the string object str1 = 17

 

Operation: ptr1= str1.data()

The string object pointed by ptr1 is: Testing the c_str

 

Operation: strlen(ptr1)

The length of character array str1 = 17

 

Operation: *cstr1 = str1.c_str()

The C-style string c_str1 is: Testing the c_str

 

Operation: strlen(cstr1)

The length of C-style string str1 = 17

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index