C++Talk.NET Forum Index C++Talk.NET
C++ language newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

How to convert char * to string
Goto page 1, 2  Next
 
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated)
View previous topic :: View next topic  
Author Message
LinuxGuy
Guest





PostPosted: Tue Mar 15, 2005 3:58 pm    Post subject: How to convert char * to string Reply with quote




Can someone please tell me how to convert

1) char * to string in c++ and
2) string to char *


Thank you


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
Victor Bazarov
Guest





PostPosted: Tue Mar 15, 2005 8:25 pm    Post subject: Re: How to convert char * to string Reply with quote



LinuxGuy wrote:
Quote:
Can someone please tell me how to convert

1) char * to string in c++ and

Just construct your string from the pointer.

Quote:
2) string to char *

There is no simple way if you really want a pointer to non-const
char as you wrote (char *). If you can live with 'const char *',
then use 'c_str()' member function of the 'string' class.

V

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Daniel T.
Guest





PostPosted: Tue Mar 15, 2005 8:36 pm    Post subject: Re: How to convert char * to string Reply with quote



"LinuxGuy" <rahul.ruikar (AT) gmail (DOT) com> wrote:

Quote:
Can someone please tell me how to convert

1) char * to string in c++ and
2) string to char *

void char_string( char* c ) {
std::string s( c );
}

void string_char( string s ) {
const char* c = s.c_str();
}

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Falk Tannhäuser
Guest





PostPosted: Tue Mar 15, 2005 8:43 pm    Post subject: Re: How to convert char * to string Reply with quote

LinuxGuy wrote:
Quote:
Can someone please tell me how to convert
1) char * to string in c++ and

char const msg[] = "HelloLinuxGuy!";

// using constructors:
std::string s1(msg); // Now s1 == "Hello" (stops at first embedded '' character)
std::string s2(msg, sizeof(msg)-1); // Now s2 == "HelloLinuxGuy!"

// using assignment operator
std::string s3; s3 = msg; // Now s3 == "Hello"

// using assign() member function
std::string s4; s4.assign(msg); // Now s4 == "Hello"
std::string s5; s5.assign(msg, sizeof(msg)-1); // Now s5 == "HelloLinuxGuy!"

Many other std::string member functions, as append(), insert(), replace() ...
also accept "char const*" both to ''-terminated strings or with explicitly
specifying the length (and thus allowing for embedded '' characters).

Quote:
2) string to char *
There is no direct conversion - but there are conversions to "char const*":

std::string s("abc");

char const* pc1 = s.c_str(); // Guaranteed to point to a ''-terminated string

char const* pc2 = s.data(); unsigned size_pc2 = s.size();
// Not necessarily ''-terminated but potentially more efficient; check size()
// to know the useful length (would be 3 for "abc")

Note that these pointers become invalid when the string they originate from
is modified or destroyed, and that you must not try to modify the data they
point to - that's why there is the "const".

Falk

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
wittempj@hotmail.com
Guest





PostPosted: Tue Mar 15, 2005 8:59 pm    Post subject: Re: How to convert char * to string Reply with quote

Is this what you want?

-#include <iostream>
-#include <string>

-int main()
-{
- std::string s("this is a string");
- const char* p;
- const char z[] = "This is a char*";

- p = s.c_str();
- std::cout << p << std::endl;

- std::cout << z << std::endl;

- s = z;

- std::cout << s << std::endl;

- return 0;
-}


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Allan W
Guest





PostPosted: Tue Mar 15, 2005 9:00 pm    Post subject: Re: How to convert char * to string Reply with quote

LinuxGuy wrote:
Quote:
Can someone please tell me how to convert

1) char * to string in c++ and

std::string(ptr)

Quote:
2) string to char *

The answer to this part is more complicated. You can get a const char*
by using c_str() -- there are rules for how long that pointer is valid,
but the gist is, "until you modify the string in any way."


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Michael Etscheid
Guest





PostPosted: Tue Mar 15, 2005 9:01 pm    Post subject: Re: How to convert char * to string Reply with quote

LinuxGuy schrieb:

Quote:
Can someone please tell me how to convert

1) char * to string in c++ and
2) string to char *


#include <string>

const char *const foo = "foo";
std::string baz = foo;
const char *const bar = baz.c_str();

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Darren Bane
Guest





PostPosted: Tue Mar 15, 2005 9:03 pm    Post subject: Re: How to convert char * to string Reply with quote

char *from = "Hello World!";
char to[LINE_MAX];

string s(from); // answers (1)
strcpy(to, s.c_str()); // answers (2)


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Ben Hutchings
Guest





PostPosted: Wed Mar 16, 2005 8:50 am    Post subject: Re: How to convert char * to string Reply with quote

LinuxGuy wrote:
Quote:

Can someone please tell me how to convert

1) char * to string in c++ and

Assuming that the pointers point to standard null-terminated strings,
then just pass them to the string constructor. If they point to
fixed-length strings, pass pointer and length to the string
constructor instead. The null-terminated strings will be copied into
the string objects.

Quote:
2) string to char *

The string member function c_str() returns a pointer to a null-
terminated string equivalent to the string object [*]. The return
type is const char *; you can use const_cast to convert this to char *
but you must not use the pointer to modify the string. The pointer
becomes invalid if the string is modified in any way.

[*] Except that since string objects contain counted rather than
null-terminated character sequences, they may contain embedded
nulls, which may cause problems for functions that only deal
with null-terminated strings.

--
Ben Hutchings
Having problems with C++ templates? Your questions may be answered by
<http://womble.decadentplace.org.uk/c++/template-faq.html>.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Ali Çehreli
Guest





PostPosted: Wed Mar 16, 2005 8:52 am    Post subject: Re: How to convert char * to string Reply with quote

"LinuxGuy" <rahul.ruikar (AT) gmail (DOT) com> wrote

Quote:

Can someone please tell me how to convert

1) char * to string in c++ and
2) string to char *

I will assume that by "char *" you mean a C-style string and by "string" you
mean std::string of C++.

Technically, 'char *' is the type of a pointer that points to a single
character. What makes it a C-style string is the way we treat that and the
following characters. All of the characters are part of the string up to and
including the null character ('').

We cannot convert a C-style string to std::string, but we can make a
std::string from the characters pointed to by the char* pointer. std::string
has a constructor that does exactly this:

void foo(char * message)
{
// Making a std::string out of 'char *'

std::string another_message = message;
}

The good (and the bad) thing is that, the string constructor that takes a
'char *' is implicit, meaning that any 'char *' can be used to construct a
string automatically whenever a 'char *' is used in place of a std::string:

void bar(std::string const & something);

void foo(char * message)
{
// A temporary std::string will be created automatically
// before calling bar:

bar(message);
}

Accessing the characters of a std::string as a C-style string is done
through its c_str() member function; but the type of the result is 'char
const *', not 'char *':

void takes_C_string(char const * something);

void foo2(std::string const & message)
{
takes_C_string(message.c_str());
}

If you need a modifiable C-style string that contains the characters of a
std::string, you must copy those characters to some place that is owned by
you.

Ali


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Vlad
Guest





PostPosted: Wed Mar 16, 2005 8:56 am    Post subject: Re: How to convert char * to string Reply with quote

From char* to std::string:

char* c;
std::string s;

make sure c isn't null and then do either
s = c;
or
s.assign(c);


From std::string to const char*:
const char* c = s.c_str();

I don't think there is a good reason of converting std::string into char*.
But if you don't really care about reasons you can always use c_str() and
then apply an ugly cast from const char* to char*.

Regards.


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
Back to top
Mihnea
Guest





PostPosted: Thu Mar 17, 2005 8:10 am    Post subject: Re: How to convert char * to string Reply with quote

"Darren Bane" <pangur (AT) utvinternet (DOT) ie> wrote

Quote:
char *from = "Hello World!";
char to[LINE_MAX];

string s(from); // answers (1)
strcpy(to, s.c_str()); // answers (2)


Please note that when creating a string from a const char* using the

syntax std::string(const char*), the const char * must not be null,
otherwise you will get an access violation on VC6.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
kanze@gabi-soft.fr
Guest





PostPosted: Thu Mar 17, 2005 8:11 am    Post subject: Re: How to convert char * to string Reply with quote

Ali Çehreli wrote:
Quote:
"LinuxGuy" <rahul.ruikar (AT) gmail (DOT) com> wrote in message
news:1110874487.055590.234900 (AT) g14g2000cwa (DOT) googlegroups.com...

Can someone please tell me how to convert

1) char * to string in c++ and
2) string to char *

I will assume that by "char *" you mean a C-style string and
by "string" you mean std::string of C++.

And that the results of the conversion was, in both cases, a
string with the same text value.

I think we all assumed that, although arguably, based literally
on what he wrote, and not taking into account a number of common
idioms, what he wanted would be more along the lines of:

std::ostringstream s ;
s << (void*)myCharStart ;
s.str() ;

That really converts a char* into a string:-).

(And you do well to remind us of our sloppiness in thinking
here.)

[...]
Quote:
We cannot convert a C-style string to std::string, but we can
make a std::string from the characters pointed to by the char*
pointer.

And what would convert X into Y mean otherwise? If you convert
an int into a double, you get a new object. If you convert a
null terminated sequence of char's into an std::string, you get
a new object. The result of conversions between object types is
always a new object (an rvalue). We often forget this in the
case of pointers, because the object being converted is a
pointer; we get a new pointer object, but it points to the same
object as the original pointer.

And of course, this rule doesn't apply for conversions to
reference types.

[...]
Quote:
If you need a modifiable C-style string that contains the
characters of a std::string, you must copy those characters to
some place that is owned by you.

Since nobody else seems to have mentioned this, I will also
point out that std::string has a member function which does just
this. Called, curiously enough, copy. So you can do something
like:

char buffer[ probablyBigEnough ] ;
char* pBuffer = ( myString.size() < probablyBigEnough
? buffer
: new char[ myString.size() + 1 ] )
;
someLegacyFunctionWhichModifiesACStyleString( pBuffer ) ;
myString = pBuffer ;
if ( pBuffer != buffer ) {
delete [] pBuffer ;
}

(Of course, you'll certainly want to wrap up that buffer
management in a RAII class.)

--
James Kanze GABI Software
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Jeff Schwab
Guest





PostPosted: Thu Mar 17, 2005 12:27 pm    Post subject: Re: How to convert char * to string Reply with quote

LinuxGuy wrote:
Quote:
Can someone please tell me how to convert

1) char * to string in c++ and
2) string to char *

#include <string>
#include <cstring>

int main ( )
{
std::string s = "Hello, world."; // 1
char const* p = std::strcpy( new char[ s.size( ) ], // 2
s.c_str( ) );

delete [ ] p; // Don't forget.
}

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Back to top
Ben Hutchings
Guest





PostPosted: Sat Mar 19, 2005 1:00 am    Post subject: Re: How to convert char * to string Reply with quote

Jeff Schwab wrote:
<snip>
Quote:
int main ( )
{
std::string s = "Hello, world."; // 1
char const* p = std::strcpy( new char[ s.size( ) ], // 2
s.c_str( ) );
snip


Off by one.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


Back to top
Display posts from previous:   
Post new topic   Reply to topic    C++Talk.NET Forum Index -> C++ Language (Moderated) All times are GMT
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.