Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String question?

Status
Not open for further replies.

Sidro

MIS
Sep 28, 2002
197
US
hi,
Does anyone know how to take a string value and copy it into a char array? Ex.

string name="Tek-tips.com";
I want to put that into a char NewName[13];
 
What I would do is to use strcpy() or strncpy() like this:


Code:
strncpy(newName, name.c_str(), strlen(name.c_str())) ;

Hope this helps! [thumbsup] Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.

- janvier -
 
or strcpy( newName, name.c_str() ). Both are member functions of string.h .
 
thanks for all your help. I do have one last question about strings. You both showed me how to go from string to char. Now how do I put a single char into a string?
example,

char A[1];
A='j';
string Name="Hi!";

I would like C++ to attach 'j' to string name so it looks like this," Hi! j "
 

Code:
char A[1];
     A='j';

This should be:

Code:
char A[2];
     A[0]='j';
     A[1]= 0;

...or simply:

char A[2] = "j";

..or...

char A[] = "j";

Anyway, if the STL supports it you may be able to do:

Code:
char A = 'j';
string Name="Hi!";
Name += A;

...and if not, just use above array code and do the same.
 
I've never used the function yet (I'm not that far along in my textbook), but it seems as if the insert function will work.

You pass the index of insertion (placed before index) and the char * or string to insert as arguements.

Tell me if this works.

char *A = " J";

Name.insert( 3, A );

 
Just a quick note on

char A[1] = "j";

This is illegal on C89 but legal on C99. Since VC++ is not C99 compliant, it is illegal but it may be legal on the next release of the compiler.
 
Hey, if anyone's still reading this, I've never seen such a statement as A[] = 'j' without a subscript. What exactly does it do?
 
Heh heh.

I assume you mean something like:

[tt]char A[] = "j" // note the double quotes[/tt]

It makes the size of the array exactly big enough to hold that string. 2 in this case (one for 'j', one for '\0').

You can also do something like:

[tt]int B[] = { 20, 30, 60, 40 };

And it will make B exactly large enough to hold all that stuff (4 in this case).
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top