[Search for users] [Overall Top Noters] [List of all Conferences] [Download this site]

Conference turris::c_plus_plus

Title:C++
Notice:Read 1.* and use keywords (e.g. SHOW KEY/FULL KIT_CXX_VAX_VMS)
Moderator:DECCXX::AMARTIN
Created:Fri Nov 06 1987
Last Modified:Thu Jun 05 1997
Last Successful Update:Fri Jun 06 1997
Number of topics:3604
Total number of notes:18242

3552.0. "convert int to string" by CIM2NI::THORPE () Wed Apr 23 1997 15:00

I can't believe I can't find the answer to this on my own...

How do I convert an int to a string?  The following code fragment gets the
point across but seems likely to overflow...

main()
{
  String s;
  int blah = 404;

  sprintf ( s, "%d", blah );
}

Thanks,
Bill
T.RTitleUserPersonal
Name
DateLines
3552.1SPECXN::DERAMODan D'EramoWed Apr 23 1997 15:4610
        You can avoid the overflow by sprintf-ing to a char array
        first...
        
        	int blah = 404;
        	char buffer[SOME_SAFE_BUT_NOT_TOO_EXTRAVAGANT_BOUND];
        	int n = sprintf(buffer, "%d", blah); // this is truly...
        	assert(0 <= n && n < sizeof buffer); // ...paranoid :-)
        	String s(buffer);
        
        Dan
3552.2CIM2NI::THORPEWed Apr 23 1997 15:586
I was hoping there was a way without having to dummy up a
char array - I guess I can stop wondering now.

Thanks Dan.

-Bill
3552.3SPECXN::DERAMODan D&#039;EramoWed Apr 23 1997 16:148
        There are "string streams" which you can create, write to with
        a sequence of "<<" operations, and then extract the entire
        text written to them.  That also has an intermediate
        something, the stream.  You can always define a function or
        operator that takes a 'String &' and an 'int' and does the
        work on an already constructed string.
        
        Dan