copying a string

Started by
4 comments, last by commando_337 22 years, 6 months ago
ok...should be simple enough how do i copy one string to another for example, if i have string1 = "Hello"; string2 = "Goodbye"; and i want to copy string2 to string1, iwould think strcpy(string1, string2); but my compiler REALLY doesnt'' like this...what am i supposed to use
Advertisement
I assume this is in c++



char string1[20];
strcpy(string1, "Hello");

char string2[20];
strcpy(string2, "Goodbye");

strcpy(string1, string2);

...
Move toSTL:
#include using std::string;string string1, string2, string3;string1 = "Hello", string2 = "Goodbye";string3 = string1; string3 += string2;    
actually C++ would be

#include std::string string1("Hello");std::string string2("Goodbye");std::string string3;string1+=string2; // if you want to append string1 to string2string3 = string1+string2; // if you want string 1 and 2 untouched 


in C you can eighter use strcat or sprintf
char string1[] = "Hello";char string2[] = "Goodbye";char string3[255] = "";// strcat version:strcat(string3,string1); // append string 1 to string 3 (empty)strcat(string3,string2); // append string 1 to string 3 (containing string 1)// sprintf version:sprintf(string3,"%s%s",string1,string2);//in both cases string2 ends up with the result you want. 

remember the brackets [] to make a char array instead of a char single char variable
sorry for the double post, came up wrong and as anon, cant change it

actually C++ would be

  #include <string>std::string string1("Hello");std::string string2("Goodbye");std::string string3;string1+=string2; // if you want to append string1 to string2string3 = string1+string2; // if you want string 1 and 2 untouched  


in C you can eighter use strcat or sprintf
  char string1[] = "Hello";char string2[] = "Goodbye";char string3[255] = "";// strcat version:strcat(string3,string1); // append string 1 to string 3 (empty)strcat(string3,string2); // append string 1 to string 3 (containing string 1)// sprintf version:sprintf(string3,"%s%s",string1,string2);//in both cases string2 ends up with the result you want.   

remember the brackets [] to make a char array instead of a char single char variable
Thanks, i got it working...for some reason, i think i may have missed something somewhere...

This topic is closed to new replies.

Advertisement