Arm Mbed OS support forum

Problem with string merging

Hello,

I’ve problem to merge two strings. Here is the code.

Here is result:

string_1 before merging: String1
string_1 after merging: !x’

instead of:

string_1 before merging: String1
string_1 after merging: String1 String2

As you can see above I’ve problem with string_1 after merging with string_2. Do you know where is the problem ?

I’m using mbed studio with latest mbed-os master.

Best regards
Maciek

Code:
#include “mbed.h”
#include

// SERIAL PINS
static BufferedSerial dbg ( PA_9 , NC , 115200 ) ;

// main() runs in its own thread in the OS
int main ()
{
//DBG configuration
dbg.set_format ( 8 , BufferedSerial::None , 1 ) ;

std::string string_1 ( "String1 " ) ;
std::string string_2 ( "string2" ) ;

dbg.write ( "\r\nstring_1 before merging: " , sizeof ( "\r\nstring_1 before merging: " ) ) ;
dbg.write ( &string_1 , sizeof ( string_1 ) ) ;

string_1 += string_2 ;
//string_1.append (string_2 ) ;
dbg.write ( "\r\nstring_1 after merging: " , sizeof ( "\r\nstring_1 after merging: " ) ) ;
dbg.write ( &string_1 , sizeof ( string_1 ) ) ;
}

I think you need to convert it to c style string.

dbg.write(string_1.c_str(), string_1.length());

Thanks a lot! It works now.