convert char array to string

Hi,

Trying to get this code to work, but keep getting junk for the ouput.


1
2
3
4
  const char * larray;  
 larray="this is  a test";     
 string strlist = larray;     
 printf("%s\n",strlist); 



Tried doing this way based on some examples I found, but does not work.

would appreciate any help.

Thanks
no, that just won't work, because

1st) you declared larray as const char*, and yet you assigned a value to it

if you want to assign a c - string to std::string, use the string member function assign:

strlist.assign( larray );
http://www.cplusplus.com/reference/string/string/assign/

EDIT
For the people who came up to this post and have read this reply,, please just forget it,, it is a complete mess... :///
Last edited on
or use string constructor:
1
2
3
	const char* aa = "asdad";

	string str(aa);
1st) you declared larray as const char*, and yet you assigned a value to it

That's fine. const char * larray; doesn't declare a const pointer. It declares a pointer to const char.

So: the address to which the pointer points can be changed, but the values at that memory location cannot be changed.

larray="this is a test";

is fine, because it's changing the address to which the pointer points.
Last edited on
nevermore28 wrote:
1st) you declared larray as const char*, and yet you assigned a value to it
That's not a problem.

nevermore28 wrote:
if you want to assign a c - string to std::string, use the string member function assign:
No need to do that

The problem is that you provide a std::string to printf while expects a c-string:

printf("%s\n",strlist.c_str());

solves the problem.
@MikeyBoy and @coder777 ->
oh i see, i didn't figure that out ( i'm just a begginer too ) ,by the way ... thanks to the two of you for the right info
You're welcome :)

The difference between

1
2
// pointer is non-const, but the char being pointed to is const.
const char* larray;

and

1
2
// pointer is const, but the char being pointed to is non-const
char* const larray;

is a subtle one, but worth taking the time to understand.
Last edited on
@coder777, Mikeyboy, and Tath -->

the string str(aa); // worked fine and using cout instead of printf also corrected some output problems I had. Thank you!!
Topic archived. No new replies allowed.