char array to string?

P

pentiumPunk

Hi, I created an array of characters and want to convert that array to a
string.
I want to do something like this :

char array1 [25]; //with letters already in it
string string1;
string1 = array1;

That wont work will it? what would be the proper syntax? thanks in ahead!
 
N

Noah Roberts

pentiumPunk said:
Hi, I created an array of characters and want to convert that array to a
string.
I want to do something like this :

char array1 [25]; //with letters already in it
string string1;

Change to "string string1(array);" assuming that your char array is null
terminated.

NR
 
I

Ivan Vecerina

pentiumPunk said:
Hi, I created an array of characters and want to convert that array to a
string.
I want to do something like this :

char array1 [25]; //with letters already in it
string string1;
string1 = array1;

That wont work will it? what would be the proper syntax? thanks in ahead!

If the string in array1 is null-terminated:
string1.assign( array1 );
or, better, direct initialization:
string string1( array1 );

If array1 is not null-terminated:
string1.assign( array1, array1+25 );
or: string1.assign( array1, 25 );
And there is a pair of matching constructors that
accept the same parameters:
string string1( array1, array1+25 );
or: string string1( array1, 25 );

Too much choice indeed...

hth
 
J

John Harrison

pentiumPunk said:
Hi, I created an array of characters and want to convert that array to a
string.
I want to do something like this :

char array1 [25]; //with letters already in it
string string1;
string1 = array1;

That wont work will it?

Why not? C++ is easier than you think.
what would be the proper syntax? thanks in ahead!

Very slightly better is to construct the string instead of assigning to it.

char array1 [25]; //with letters already in it
string string1(array1);

I'm assuming that array1 is null terminated. If not you should write

char array1 [25]; // with 25 letters already in it
string string1(array1, 25);

john
 
S

Shane Beasley

pentiumPunk said:
char array1 [25]; //with letters already in it
string string1;
string1 = array1;

That wont work will it? what would be the proper syntax? thanks in ahead!

Yes, that will work... Didn't you try it before posting here?

- Shane
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top