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:
- 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