Copy const char* to char*

Hello again,
I'm a bit confused... I have a std::string szLine which reads in a line of a document. I don't want to directly modify this line, so I create a temporary char*.

1
2
3
4
5
6
std::string szLine;

while( true ) {
	char *szBuffer = (char*)szLine.c_str( );
	strcpy( szBuffer, "Bla" );
}


Modifying szBuffer also modifies szLine, which I actually don't want. I suppose this is due to the (char*). What can I do to simply copy the string and don't make a pointer to szLine???

Thanks in advice,
DarkDragon1993
dynamic memory allocation!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
std::string szLine;

while( true ) {
     //...
     //get szLine somehow...
     //...
     
     char *szBuffer = new char[szLine.size()+1];
     strcpy(szBuffer,szLine.c_str( ));

     //now do whatever you want with szBuffer...
     //...

     //but when your'done don't forget to free the memory
     delete[] szBuffer;
}

or you could just have one more string object...

1
2
3
4
5
6
7
8
9
10
11
12
13
std::string szLine;
std::string temp;

while( true ) {
     //...
     //get szLine somehow...
     //...

     temp=szLine; //so simple...

     //now do whatever you want with temp...
     //...
}
Last edited on
Topic archived. No new replies allowed.