Adding strings together

Started by
5 comments, last by sand_man 19 years, 7 months ago
I want to have one string so, char mainstring[128]. And then add 1 charactor strings to each part it. Making one big string. But im not sure how to do this. Any help?
Advertisement
http://www.cplusplus.com/ref/cstring/strcat.html

but, why use strings if it's only 1 character long? use a simple char instead and you'll save yourself a lot of headaches. then you can just add them into the mainstring inside a for loop:

for ( int i = 0; i < 128; ++i ){    char theNewChar = someFunctionThatGetsYourChar();    mainstring = theNewChar;}


-me
if your using C++, use std::string. its purpose is to simplify using strings. you can easily concatanate strings via the + operator. ex:

string first_name = "joe";string lane_name = "smith";cout << "Your name is"<< first_name + " " + last_name <<endl;


this will print out "Your name is joe smith". personally i think this makes life a million times easier then using functions. for example, you can make an error logging function which receives a single string as parameters, BUT, you dont have to send it a single string, you can concatnate strings in the function call.

string error = Get_Error();
log(" Error in function X :" + error);

sooo much nicer then using C style methods.
FTA, my 2D futuristic action MMORPG
thanks man that realy helped i was trying to do like char mainstring[1] = "a";
mainstring[2] = "b";

then expecting it to print ab. Thx for the help.
The char mainstring[1] = "a"... etc thing you were talking about would work, but don't forget to null terminate your string, otherwise you'll get "ab" followed by garbage. But it's easier to use a class, like graveyard filla suggested, or you can use strcat(), like Palidine suggests. However, his loop isn't entirely correct, because of the null termination thing I mentioned.
Also, don't forget that array indices start at 0, not 1.
and dont forget that it would be
myarray[0] = 'a';

not
myarray[0] = "a";

This topic is closed to new replies.

Advertisement