How convert string to char*

Hi! I can't convert string to char*.
This is my code.

string temp;
cout<<" Enter your name: ";
cin>>temp;
char * pch = (char *) malloc(sizeof(char)*(temp.size()));
strcpy(temp, pch);

Last edited on
In C++ you could use:
while(cin.get(temp))//to get the name
and
{
cout.put(temp);//to print it
if(temp==\n)break;
}
You also need to pay some close attention to little details.
You've got an off-by-one error and the arguments to strcpy() are reversed.
I also recommend staying away from >> when inputting strings.
1
2
3
4
5
string temp;
cout << "Enter your name: ";
getline( cin, temp );
char* pch = (char*)malloc( sizeof( char ) *(temp.length() +1) );
strcpy( pch, temp.c_str() );

You can avoid #including <cstring> and strcpy() if you like by using the string's char_traits:
1
2
...
string::traits_type::copy( pch, temp.c_str(), temp.length() +1 );

Hope this helps.
Last edited on
Topic archived. No new replies allowed.