In: Computer Science
How am I supposed to implement a c_str method that returns a c string representation of a String object? I need to return a csting representation of a string object. I am confused on what cstrings are and where to go.
method signature is as follows:
char* c_str();
Please find the code below:::
#include <iostream>
#include <string>
using namespace std;
char* c_str(string data){
   char * pointer;
   //get the size
   int size = data.length();
   //initialize the pointer
   pointer = new char(size);
   int i;
   //copy data
   for(i=0;i<size;i++){
       pointer[i] = data[i];
   }
   //add string break at the end
   pointer[i] = '\0';
   return pointer;
}
int main(){
   string word="hello I am here";
   char * cString = c_str(word);
   cout<<cString;
   return 0;
}
output:
