How to use c_str() without strcpy() In C++

An alternate way of Method 1 can be such, without using strcpy() function. This option will not create a new string.

Example:

C++




// C++ program to convert string
// to char array Using c_str() 
// without strcpy()
#include <cstring>
#include <string>
#include <iostream>
  
// driver code
int main()
{
    // assigning value to string s
    std::string s = "w3wiki";
    
    // the c_str() function returns
    // a const pointer to null 
    // terminated contents.
    const char* str = s.c_str();
    
    // printing the char array
    std::cout << str;
    
    return 0;
}


Output

w3wiki
  • Time complexity: O(n)
  • Auxiliary Space: O(1)

Convert String to Char Array in C++

Here, we will build a C++ program to convert strings to char arrays. Many of us have encountered the error ‘cannot convert std::string to char[] or char* data type’ so let’s solve this using 5 different methods:

  1. Using c_str() with strcpy()
  2. Using c_str() without strcpy()
  3. Using for loop
  4. Using the address assignment of each other method
  5. Using data() (C++17 and newer)

Input:

string s = "w3wiki";

Output:

char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', '\0' };

Similar Reads

1. Using c_str() with strcpy()

A way to do this is to copy the contents of the string to the char array. This can be done with the help of the c_str() and strcpy() functions of library cstring. The c_str() function is used to return a pointer to an array that contains a null-terminated sequence of characters representing the current value of the string....

2. Using c_str() without strcpy()

...

3. Using for loop

An alternate way of Method 1 can be such, without using strcpy() function. This option will not create a new string....

4. Using the address assignment of each other method

...

5. Using .data() (with C++17 or newer)

We can use for loop to iterate through each element of the std::string and assign the character to the char array one by one....