cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : Strings library : string : c_str
  Search:
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forums
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
Miscellaneous
Strings library
char_traits
classes:
· string
global functions:
· getline
· operator+
· operator<<
· operator>>
· comparison operators
· swap
string
string::string
member constants:
· string::npos
member functions:
· string::append
· string::assign
· string::at
· string::begin
· string::capacity
· string::clear
· string::compare
· string::copy
· string::c_str
· string::data
· string::empty
· string::end
· string::erase
· string::find
· string::find_first_not_of
· string::find_first_of
· string::find_last_not_of
· string::find_last_of
· string::get_allocator
· string::insert
· string::length
· string::max_size
· string::operator+=
· string::operator=
· string::operator[]
· string::push_back
· string::rbegin
· string::rend
· string::replace
· string::reserve
· string::resize
· string::rfind
· string::size
· string::substr
· string::swap

-

string::c_str public member function
const char* c_str ( ) const;

Get C string equivalent

Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.

A terminating null character is automatically appended.

The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only granted to remain unchanged until the next call to a non-constant member function of the string object.

Parameters

none

Return Value

Pointer to an internal array containing the c-string equivalent to the string content.

Example

// strings and c-strings
#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int main ()
{
  char * cstr, *p;

  string str ("Please split this phrase into tokens");

  cstr = new char [str.size()+1];
  strcpy (cstr, str.c_str());

  // cstr now contains a c-string copy of str

  p=strtok (cstr," ");
  while (p!=NULL)
  {
    cout << p << endl;
    p=strtok(NULL," ");
  }

  delete[] cstr;  
  return 0;
}

Output:

Please
split
this
phrase
into
tokens

Basic template member declaration

( basic_string<charT,traits,Allocator> )
const charT* c_str ( ) const;

See also

string::copy Copy sequence of characters from string (public member function)
string::data Get string data (public member function)
string::assign Assign content to string (public member function)

Home page | Privacy policy
© cplusplus.com, 2000-2008 - All rights reserved - v2.2
Spotted an error? contact us