Aug 6, 2008 at 5:42pm UTC
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 Aug 6, 2008 at 5:47pm UTC
Aug 20, 2008 at 5:58am UTC
In C++ you could use:
while(cin.get(temp))//to get the name
and
{
cout.put(temp);//to print it
if(temp==\n)break;
}
Aug 20, 2008 at 11:45am UTC
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 Aug 20, 2008 at 11:46am UTC