how to concatenate const char and const char*

Jul 24, 2008 at 8:51am
i am tryiny to concatenate these two strings
catch (exception& e) {
sError_ = "Standard Exception: " + e.what();
}

and it throws the follwing error

error: invalid operands of types `const char[21]' and `const char*' to binary `operator+'

is there a way around?

thanks
Jul 24, 2008 at 9:40am
Why not use the function for the concatenation of strings?
http://www.cplusplus.com/reference/clibrary/cstring/strcat.html

Perhaps like this (I don't know the lengths of exception strings, just assumed they'd be shorter than 128 characters):

1
2
3
4
5
6
7
catch (exception& e) {
sError1_ [150];
sError1_ = "Standard Exception: ";
SError2_ [128];
SError2_ = e.what();
strcat(sError1_, sError2_);
}


Edit: Yeah, my code is pretty broken, please don't use it.
Last edited on Jul 25, 2008 at 7:14am
Jul 24, 2008 at 3:54pm
You can't assign to char arrays like that.

I don't know what type of object sError_ is.

char*
1
2
3
4
5
6
7
8
size_t len = char_traits <char> ::length( e.what() );
sError_ = new char[ 21 + len ];
char_traits <char> ::copy( sError_, "Standard Exception: ", 20 );
char_traits <char> ::copy( sError_ + 20, e.what(), len + 1 );

// do something with sError_ here

delete sError_;


char[ 1000 ]; // or some other large number
1
2
3
4
5
size_t len = char_traits <char> ::length( e.what() );
char_traits <char> ::copy( sError_, "Standard Exception: ", 20 );
char_traits <char> ::copy( sError_ + 20, e.what(), len + 1 );

// do something with sError_ here 


std::string
1
2
3
4
sError_ = "Standard Exception: ";
sError_ += e.what();

// do something with sError_.c_str() here 
Topic archived. No new replies allowed.