You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@stdcxx.apache.org by "Craig Chariton (Cont.)" <ch...@roguewave.com> on 2006/07/11 17:30:42 UTC

Strange Behavior for std::string When Used With +ltoa

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

 

#include <stdlib.h>

#include <string>

#include <iostream>

 

using std::cout;

using std::endl;

using std::flush;

 

int main()

{

            long lng1 = 1000;

            long lng2 = 2000;

            

            cout << "lng1 is " << lng1 << endl;

            cout << "lng2 is " << lng2 << endl;

//          cout << "lng2 is " << ltoa(lng2) << endl;   

 

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

            cout<<s<<endl<<endl<<flush;

 

            return 0;

}

 

 

This is the output:

lng1 is 1000

lng2 is 2000

lng1 = 1000, lng2 = 1000

Notice that the lng2 value is 1000 instead of 2000 when used with +ltoa.

 

Now, uncomment the line 

cout << "lng2 is " << ltoa(lng2) << endl;

 

This is the output:

lng1 is 1000

lng2 is 2000

lng2 is 2000

lng1 = 1000, lng2 = 2000

Notice that the lng2 value is now displayed as 2000 when used with
+ltoa.

 

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?

 

Craig Chariton




Re: Strange Behavior for std::string When Used With +ltoa

Posted by Martin Sebor <se...@roguewave.com>.
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