Conversion to C-Style Pointer-Based char* Strings - C++ STL

C++ examples for STL:string

Description

Conversion to C-Style Pointer-Based char* Strings

Demo Code

#include <iostream>
#include <string>

int main(int argc, const char *argv[]) {
    std::string string1("STRINGS");  // string constructor with char* array
    const char *ptr1 = 0;            // initialize *ptr1
    int length = string1.length();
    char *ptr2 = new char[length + 1];  // including null

    // copy characters from string1 into allocated memory
    string1.copy(ptr2, length, 0);  // copy string1 to ptr2 char*
    ptr2[length] = '\0';            // add null terminator

    std::cout << "string string1 is " << string1
              << "\nstring1 converted to a C-stryle string is "
              << string1.c_str() << "\nptr1 is ";

    ptr1 = string1.data();/*from   w  w w . j av a  2 s .c  om*/

    // output each character using pointer
    for (int i = 0; i < length; ++i)
        std::cout << *(ptr1 + i);  // user pointer arithmetic

    std::cout << "\nptr2 is " << ptr2 << std::endl;

    delete[] ptr2;  // reclaim dynamically allocated memory

    return 0;
}

Result


Related Tutorials