2

I'm using a third party code which has its own implementation for std::ostream operator<<, to handle the third party's type. I'm using stringstream for this output - like:

string ToString(const thrdPartyType& structure)
{
stringstream outputStream;
outputStream<<structure;
return outputStream.str();
}
...
string str = ToString(structure);
...

This structure contains pointer members, which are set to NULL. When using the operator<< and the assignment of str() into a string, I see (via gdb - print str) that there are many leading '\000' characters, then the string data I need.

How can I trim those NULLs in order to get only the real, not empty data?

P.S. The exact code works fine in Windows VC++...

Thank you.

rkellerm
  • 5,362
  • 8
  • 58
  • 95
  • 1
    It sounds as though the third party code is broken. Maybe you should file a bug report. – Konrad Rudolph Nov 25 '10 at 15:16
  • Firstly is outputStream printable? On what platform are you running gdb. If this is printing pointers are they 64-bit where it is not working which may explain why you see more zero characters? – CashCow Nov 25 '10 at 15:44

2 Answers2

2

If you have boost available, something like the following will replace all instances of null in a string with another value.

boost::replace_all(str,boost::as_array(""),"NULL");

For example

char buf[10] = "hello";
string str(buf,buf+10);
boost::replace_all(str,boost::as_array(""),"NULL");
cout << str << endl;

Produces the following output

helloNULLNULLNULLNULLNULL
Zero
  • 1,147
  • 1
  • 9
  • 13
2

Are you looking for a workoround like this?

string ToString(const thrdPartyType& structure)
{
   stringstream outputStream;
   outputStream << structure;

   stringstream workaround;
   while(! outputStream.eof ) {
   char t;
   outputStream >> t;
   if(t != '\0')
    workaround << t;
   }

   return workaround .str();
}
onof
  • 17,167
  • 7
  • 49
  • 85