strcpy claiming error

going to compile my program and it states that it cannot convert paramter 1 from 'std:string' to 'char *'.
 
strcpy (part2, part1);


that's the line its complaining about but both have been declared as "std::string" prior to this line and part1 has text etc in it. Why is there a problem just copying it to another string?

strcpy() is a C function, while std::string is a C++ class. strcpy() is meant to be used with raw arrays of char, while std::string is a smart string class that can accomplish the copy operation differently.

1
2
3
4
5
6
const char * const myText = "Hello";
//the C way
char *copy = new char[6];
strcpy(copy, myText);
//The C++ way
std::string cppCopy = myText;


Read about strings in this website's tutorial.
Last edited on
strcpy requires pointers to characters (ie character arrays). You can get the source string with source.c_str(), but you really need to have a character array for the destination.

And, may I ask, why can you not do this?
1
2
3
std::string source = "Hello", target;
target = source;
std::cout << target;
I know too much C++ for my own good. I know things I shouldn't know and don't know other things I should know.

My string is an entire text file and I'm trying to copy it to another string so I can manipulate it while maintaining the original copy in part1. How would I copy one string to another in my case?

1
2
3
4
if (part1.find("results")!=string::npos)
{
	part1.erase(0, part1.find("results"));
}


is an example of what I'm doing to the strings to manipulate them (if its important).
is your part2 also a string. if it is it will not work . .
it have to be ..

1
2
3
4
5
6
7
8
string part2 ;
char ch_part2[50]; 
strcpy( ch_part2, part1.c_str());
part2 = ch_part2; 
if (part1.find("results")!=string::npos)
{
	part1.erase(0, part1.find("results"));
}


please correct me if i am wrong .
Last edited on
bluecoder wrote:
please correct me if i am wrong .
You are wrong, you make the ch_part2 buffer by guessing that the string will never be more than 49 characters. This is bad practice.

The simple and correct solution:
part2 = part1;
Assuming that part1 and part2 are both std::string, this will copy part1 into part2 and make them independent of each other.
Last edited on
Okay, I think I get it, but when applying that, would I still be able to manipulate part2 like it was a string as well? (IE: doing the if(part2.find("results")!=string::npos) things?) And would there be a way to not put a limitation on how many characters ch_part2 could hold? since the string is an entire html webpage.
Last edited on
dalydir, see my response.
L B, I think the clouds just parted and a heavenly light shone upon your post, thank you.
@ L B , thanks for pointing that out .. i should take care of that .. thanks
Topic archived. No new replies allowed.