Mail Archives: djgpp/1999/12/26/16:43:07
| From: | Martin Ambuhl <mambuhl AT earthlink DOT net>
|
| Newsgroups: | comp.os.msdos.djgpp
|
| Subject: | Re: Converting a string to a char *
|
| Date: | Sat, 25 Dec 1999 17:13:15 -0500
|
| References: | <840i65$auc$1 AT bob DOT news DOT rcn DOT net>
|
| X-Posted-Path-Was: | not-for-mail
|
| X-Accept-Language: | en
|
| X-ELN-Date: | 25 Dec 1999 22:12:24 GMT
|
| X-ELN-Insert-Date: | Sat Dec 25 14:15:01 1999
|
| Organization: | Nocturnal Aviation
|
| Lines: | 76
|
| Mime-Version: | 1.0
|
| NNTP-Posting-Host: | dialup-209.246.93.135.newyork2.level3.net
|
| Message-ID: | <3865417B.9AFB2909@earthlink.net>
|
| X-Mailer: | Mozilla 4.7 [en] (Win95; U)
|
| To: | djgpp AT delorie DOT com
|
| DJ-Gateway: | from newsgroup comp.os.msdos.djgpp
|
| Reply-To: | djgpp AT delorie DOT com
|
Tom wrote:
>
> I am trying to change a string to a char *. I am using the function c_str()
> but I am having problems with it.
>
> How would I go about assigning the new char * value to a char *? For
> example, this is what I
> tried to do and it didn't work. It gave me a (null) result when it should
> have said "test". Thanks.
>
> ______________________________
>
> int main()
> {
> string s = "test";
> char *b;
> *b = *s.c_str();
> cout << b;
> return 0;
> }
#include <iostream> /* mha - added */
#include <string> /* mha - added */
#include <cstring> /* mha - added */
int main()
{
string s = "test";
char *b;
*b = *s.c_str();
cout << "mha - the original code copied the value of \n"
<< " *s.c_str() [ *" << (void *)s.c_str() << "]:"
<< *s.c_str() << ", s.c_str():" << s.c_str() << "\n"
<< " to *b [ *" << (void *)b << "]:" << *b
<< ", b:" << b << "\n" << endl;
b = s.c_str(); /* mha - discards constness, beware */
cout << "mha - Now we copy the value of \n"
<< " s.c_str() [ *" << (void *)s.c_str() << "]:"
<< s.c_str() << ", s.c_str():" << s.c_str() << "\n"
<< " to b [" << (void *)b << "]:" << b
<< ", b:" << b << "\n" << endl;
cout << "s.length() = " << s.length() << endl;
b = new char[s.length()+1];
strcpy(b, s.c_str());
cout << "mha - now watch this, where we allocate some\n"
<< "space for b to point to and copy s.c_str\n"
<< " s.c_str() [ *" << (void *)s.c_str() << "]:"
<< s.c_str() << ", s.c_str():" << s.c_str() << "\n"
<< " to b [" << (void *)b << "]:" << b
<< ", b:" << b << endl;
return 0;
}
/* vi:set cindent ts=4 sw=4 et tw=72:*/
--
Martin Ambuhl mambuhl AT earthlink DOT net
What one knows is, in youth, of little moment; they know enough who
know how to learn. - Henry Adams
A thick skin is a gift from God. - Konrad Adenauer
__________________________________________________________
Fight spam now!
Get your free anti-spam service: http://www.brightmail.com
- Raw text -