c++ string to c code example

Example 1: c c_str

Get C string equivalent

  TL;DR	->	Makes the string end with '\0'

Returns a pointer to an array that contains a null-terminated sequence of
characters (i.e., a C-string) representing the current value of the string
object.

This array includes the same sequence of characters that make up the value of
the string object plus an additional terminating null-character ('\0') at the
end.

Example 2: COnvert string to char * C++

// CPP program to convert string 
// to char array 
#include <bits/stdc++.h> 
  
using namespace std; 
  
// driver code 
int main() 
{ 
    // assigning value to string s 
    string s = "geeksforgeeks"; 
  
    int n = s.length(); 
  
    // declaring character array 
    char char_array[n + 1]; 
  
    // copying the contents of the 
    // string to char array 
    strcpy(char_array, s.c_str()); 
  
    for (int i = 0; i < n; i++) 
        cout << char_array[i]; 
  
    return 0; 
}

Tags:

C Example