How to use c_str() with strcpy() In C++
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.
const char* c_str() const;
If there is an exception thrown then there are no changes in the string. But when we need to find or access the individual elements then we copy it to a char array using strcpy() function. After copying it, we can use it just like a simple array. The length of the char array taken should not be less than the length of an input string.
In order to create a new array to contain the characters, we must dynamically allocate the char array with new. We also must remember to use delete[] when we are done with the array. This is done because, unlike C, C++ does not support Variable Length Arrays (VLA) on the stack.
Example:
C++
// C++ program to convert string // to char array using c_str() #include <cstring> #include <string> #include <iostream> // driver code int main() { // assigning value to string s std::string s = "w3wiki" ; const int length = s.length(); // declaring character array (+1 for null terminator) char * char_array = new char [length + 1]; // copying the contents of the // string to char array strcpy (char_array, s.c_str()); for ( int i = 0; i < length; i++) { std::cout << char_array[i]; } delete [] char_array; return 0; } |
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:
- Using c_str() with strcpy()
- Using c_str() without strcpy()
- Using for loop
- Using the address assignment of each other method
- 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' };
Contact Us