Craig Chariton (Cont.) wrote:
I am seeing some strange behavior with HP-UX 11.11 and aCC A.3.xx
compilers.  Here is the test code:

[...]
Is this a problem with the + operator in std::string?  The ltoa seems to
work okay by itself.  Why does adding the line cout << "lng2 is " <<
ltoa(lng2) << endl; make the +ltoa display the correct value?

ltoa() returns a pointer to an internal buffer which it overwrites
each time it's called.

From the HP-UX ltostr(3C) man page:

  WARNINGS

  The return values for ltostr(), ultostr(), ltoa() and ultoa() point
  to data whose content is overwritten by subsequent calls to these
  functions by the same thread.

http://docs.hp.com/en/B2355-90694/ltostr.3C.html

Saving a copy of the string it points to before calling it again
would be one (inefficient) way of dealing with it:

    std::string s =
          std::string("lng1 = ")+std::string (ltoa(lng1))
        +", lng2 ="+std::string (ltoa(lng2));

A better way would be to use ostringstream to format the numbers:

#include <sstream>
#include <iostream>

int main ()
{
    const long lng1 = 1000;
    const long lng2 = 2000;

    std::cout << "lng1 is " << lng1 << '\n'
              << "lng2 is " << lng2 << '\n';

    std::ostringstream strm;
    strm << "lng1 = " << lng1 << ", lng2 = " << lng2;

    std::cout << strm.str () << '\n';
}

Martin

Reply via email to